在excel中未正确保存上瘾字符

时间:2016-10-05 09:17:20

标签: c# excel

我有以下C#代码将Umlaute字符写入csv文件。 打开文件后,这些字符完全失真。 这是代码:

string csvFile = string.Empty;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{
    //DataTable columns are already formatted WRT commas and double quotes
    for (int i = 0; i < dt.Rows.Count; i++)
         csvFile += String.Join(",", dt.Rows[i].ItemArray) + "\r\n";

    file.WriteLine(csvFile);
}

我检查了字符串'csvFile',它确实正确地保存了这些字符。 这是excel问题还是在我的代码中?

1 个答案:

答案 0 :(得分:2)

您没有将正确的BOM字符添加到输出文件中,因此Excel不知道它应该使用的编码。为了避免这种情况,请尝试将编码添加到您的Streamwriter中,如下所示:

System.IO.StreamWriter file = new System.IO.StreamWriter(fileName, new UTF8Encoding(true))

编辑:正如stuartd所述,这可能无法在每个Excel版本中正常运行