2017-05-31 34 views
0

我有這個代碼用於我的應用程序導出datagridview作爲CSV文件。它工作正常,但CSV不正確顯示單元格的值。看到下面的圖片,我也粘貼了我的代碼。我可以更改此代碼以解決此問題?爲什麼csv文件在導出時不顯示特殊字符?

下面是在DataGridView

enter image description here

這是導出CSV和它這樣表示

enter image description here

這裏是我的代碼

public void writeCSV(DataGridView gridIn, string outputFile) 
    { 

     //test to see if the DataGridView has any rows 
     if (gridIn.RowCount > 0) 
     { 
      string value = ""; 
      DataGridViewRow dr = new DataGridViewRow(); 
      StreamWriter swOut = new StreamWriter(outputFile); 


      //write header rows to csv 
      for (int i = 0; i <= gridIn.Columns.Count - 1; i++) 
      { 
       if (i > 0) 
       { 
        swOut.Write(","); 
       } 
       swOut.Write(gridIn.Columns[i].HeaderText); 
      } 

      swOut.WriteLine(); 

      //write DataGridView rows to csv 
      for (int j = 0; j <= gridIn.Rows.Count - 2; j++) 
      { 
       if (j > 0) 
       { 
        swOut.WriteLine(); 
       } 

       dr = gridIn.Rows[j]; 

       for (int i = 0; i <= gridIn.Columns.Count - 1; i++) 
       { 
        if (i > 0) 
        { 
         swOut.Write(","); 
        } 

        value = dr.Cells[i].Value.ToString(); 
        //replace comma's with spaces 
        value = value.Replace(',', ' '); 
        //replace embedded newlines with spaces 
        value = value.Replace(Environment.NewLine, " "); 

        swOut.Write(value); 
       } 
      } 
      swOut.Close(); 
     } 
    } 
+0

你可以在記事本中打開CSV您需要設置正確的文本編碼?我敢打賭,這是擅長破壞數值。 –

+0

查找BOM(字節順序標記),並注意數值精度的差異是Excel和您的應用程序之間的差異。查看[this](http://www.techrepublic.com/article/displaying-values-with-more-than-12-characters-in-excel/)瞭解更多信息。 – john

回答

3

您需要設置S的編碼treamWriter:

StreamWriter swOut = new StreamWriter(outputFile, System.Text.Encoding.UTF8); 

例如UTF-8。

和Excel中剛剛顯示的數字5.027E + 13。您可以將單元格的文本格式更改爲數字,並且Excel會向您顯示數值。或者在記事本中打開csv文件,你會看到數字是正確的。

+1

感謝此工作 – user1353519

0

導出數據時爲csv文件,如System.Text.Encoding.UTF8

0
StreamWriter swOut = new StreamWriter(outputFile, System.Text.Encoding.UTF8); 
+0

@NikBo的同一個答案 –