Hi,
I never used CSV Helper before so, I don't how to use that to write data into CSV file from sql server query result.
Currently, I am using below code which is working fine to write in to csv file. In this code I had to write couple of condition to include double quotes for column which has comma (,) included.
So, how do i use CSV Helper to include double quotes for all my string columns?
Thank you for any help in advance.
What I have tried:
using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.Add(new SqlParameter("@pick_ticket_no", pick_ticket_no));
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds, "QB");
DataTable dt = ds.Tables["QB"];
if (dt.Rows.Count > 0)
{
FTPUpload = true;
StreamWriter sw = new StreamWriter(@"C:\Export\data_" + DateTime.Now.ToString("MMddyyyyHHmmss") + ".csv", false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (dr[i].ToString().Contains(","))
{
sw.Write("\"{0}\",", dr[i].ToString());
}
else
{
sw.Write(dr[i].ToString());
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}