我有這個代碼用於我的應用程序導出datagridview作爲CSV文件。它工作正常,但CSV不正確顯示單元格的值。看到下面的圖片,我也粘貼了我的代碼。我可以更改此代碼以解決此問題?爲什麼csv文件在導出時不顯示特殊字符?
下面是在DataGridView
這是導出CSV和它這樣表示
這裏是我的代碼
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();
}
}
你可以在記事本中打開CSV您需要設置正確的文本編碼?我敢打賭,這是擅長破壞數值。 –
查找BOM(字節順序標記),並注意數值精度的差異是Excel和您的應用程序之間的差異。查看[this](http://www.techrepublic.com/article/displaying-values-with-more-than-12-characters-in-excel/)瞭解更多信息。 – john