Click here to Skip to main content
14,449,862 members
Rate this:
Please Sign up or sign in to vote.
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 21:28pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100