Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have been assigned a task where I am fetching some records from Database in data table and then I am exporting it to .csv file. the file is being written properly but the formatting is not there i mean everything is coming under on cell only.
Can smeone plsss help where m I going wrong ??
My code is gvn here:-
C#
private static void CreateCSVFile(DataTable dt, string strFilePath, string webServerFileLink)
{
   // Create the CSV file to which grid data will be exported.
   StreamWriter sw = new StreamWriter(strFilePath, false);

   // First we will write the headers.              
   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);

   // Now write all the rows.
   foreach (DataRow dr in dt.Rows)
   {
      for (int i = 0; i < iColCount; i++)
      {
         if ((!Convert.IsDBNull(dr[i])) && (i == 7))
         {
            sw.Write(dr[i].ToString().Replace("\r", " "));
         }
         else
         {
            sw.Write(dr[i].ToString().Replace(",", " "));
         }

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

      sw.Write(sw.NewLine);
   }

   sw.Close();
}


[Edit] Code formatting.
Posted
Updated 9-May-12 23:26pm
v2
Comments
Zoltán Zörgő 10-May-12 8:20am    
You cannot skip null values! Treat them as empty strings.
Sergey Alexandrovich Kryukov 10-May-12 14:58pm    
Why doing it?
--SA

I think this is a waste of your time. Who cares if CSV files are formatted well or not? Who works with them manually? They a mostly used to transfer data from one system to another or something like that. After all, create some software which represents any CSV in a form of some data grid or just use some available spreadsheet software. Or convert CSV to HTML.

Text files are not really designed to present table-like data. Your method is based on fixed-width font, which are rarely used. If you use tabs, it may look good in one editor and gets mangled in another one just because the tab widths are different. You are just dealing with dirt. Don't waste your time on it.

—SA
 
Share this answer
 
v2
Comments
Monjurul Habib 11-May-12 1:22am    
well said, 5!
Sergey Alexandrovich Kryukov 11-May-12 10:35am    
Thank you, Monjurul.
--SA
If you mean that when you open the CSV file in Excel, everuthing is in one cell. If that's the case, the likeliest reason is that you have a mismatch in the list separator. When opening the CSV, check that you're using the correct delimiter.
 
Share this answer
 

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