我正在使用 Asp.net mvc 生成一个 CSV 文件,但是我遇到了葡萄牙语特殊字符的问题。我正在使用以下代码返回文件:
public FileContentResult RelMatriculas(RelRematriculaVM model)
{
string fileContent = GenerateTheFile();
Response.Charset = "utf-8";
Response.ContentEncoding = Encoding.UTF8;
return File(new UTF8Encoding().GetBytes(fileContent), "text/csv", "RelMatriculas.csv");
}
我将 utf8 设置为编码,但是当保存文件并尝试在 Excel 中打开它时,我看到的是垃圾字符而不是特殊字符。
如果我只是在记事本中打开文件并保存它,然后在 excel 上再次打开它,则可以正确显示字符。我是否缺少将文件输出为 UTF8 的内容?
最佳答案
问题是 Excel 需要 BOM。来自 this SO answer :
var data = Encoding.UTF8.GetBytes(fileContent);
var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
return File(result, "text/csv", "RelMatriculas.csv");
关于c# - 编码导出 CSV 文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55246981/