eugeneK
eugeneK

Reputation: 11136

How to create CVS file out of DB dataset using C#?

How do i quickly create CVS (Comma Delimited File Excel) file from DB sp? I just load values with comma and what do i need to do with new line "\n" or what? Maybe there is method of Dataset to convert to CVS like ie. to XML ?

thanks

Upvotes: 0

Views: 393

Answers (1)

CD..
CD..

Reputation: 74176

        public static void CreateCsvFile(DataTable dt, string strFilePath, bool exportColumnHeaders)
        {
            using (StreamWriter sw = new StreamWriter(strFilePath, false, Encoding.UTF8))
            {
                int iColCount = dt.Columns.Count;

                if (exportColumnHeaders)
                {
                    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 (!Convert.IsDBNull(dr[i]))
                            sw.Write("\"" + dr[i] + "\"");

                        if (i < iColCount - 1)
                            sw.Write(",");
                    }

                    sw.Write(sw.NewLine);
                }

                sw.Close();
            }
        }

Upvotes: 1

Related Questions