RD Design

RD Design

  • NA
  • 25
  • 26.7k

Why csv file doesnt show special characters when export?

May 31 2017 8:18 AM
Hi,

I have this code used on my application to export datagridview as csv file.It worked fine but csv doesnt show cell values correclty.See below images and I have pasted my code as well.What can I change on this code to fix this?
 
Here is the datagridview



This is the exported csv and it shows like this



Here is my code

  1. public void writeCSV(DataGridView gridIn, string outputFile)  
  2.         {  
  3.                
  4.             //test to see if the DataGridView has any rows  
  5.             if (gridIn.RowCount > 0)  
  6.             {  
  7.                 string value = "";  
  8.                 DataGridViewRow dr = new DataGridViewRow();  
  9.                  StreamWriter swOut = new StreamWriter(outputFile);  
  10.                   
  11.   
  12.                 //write header rows to csv  
  13.                 for (int i = 0; i <= gridIn.Columns.Count - 1; i++)  
  14.                 {  
  15.                     if (i > 0)  
  16.                     {  
  17.                         swOut.Write(",");  
  18.                     }  
  19.                     swOut.Write(gridIn.Columns[i].HeaderText);  
  20.                 }  
  21.   
  22.                 swOut.WriteLine();  
  23.   
  24.                 //write DataGridView rows to csv  
  25.                 for (int j = 0; j <= gridIn.Rows.Count - 2; j++)  
  26.                 {  
  27.                     if (j > 0)  
  28.                     {  
  29.                         swOut.WriteLine();  
  30.                     }  
  31.   
  32.                     dr = gridIn.Rows[j];  
  33.   
  34.                     for (int i = 0; i <= gridIn.Columns.Count - 1; i++)  
  35.                     {  
  36.                         if (i > 0)  
  37.                         {  
  38.                             swOut.Write(",");  
  39.                         }  
  40.   
  41.                         value = dr.Cells[i].Value.ToString();  
  42.                         //replace comma's with spaces  
  43.                         value = value.Replace(','' ');  
  44.                         //replace embedded newlines with spaces  
  45.                         value = value.Replace(Environment.NewLine, " ");  
  46.   
  47.                         swOut.Write(value);  
  48.                     }  
  49.                 }  
  50.                 swOut.Close();  
  51.             }  
  52.         } 

Answers (3)