Click here to Skip to main content
15,662,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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();
                    }

                }
Posted
Updated 9-Feb-20 20:28pm

1 solution

 
Share this answer
 
Comments
phil.o 10-Feb-20 6:59am    
5'd
Maciej Los 10-Feb-20 7:04am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900