tags:

views:

55

answers:

1

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

+1  A: 
        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();
            }
        }
CD
@CD, thanks. Just one question. If there is already a file on server with previous calls will this call erase previous one or append to it?
eugeneK
http://msdn.microsoft.com/en-us/library/f5f5x7kt.aspx
CD
@CD, good. Thanks
eugeneK