简体   繁体   English

导出CSV文件的编码问题

[英]Problem with encoding exporting a CSV file

I'm using Asp.net mvc to generate a CSV file, but I'm having problems with special characters in portuguese language. 我正在使用Asp.net mvc生成CSV文件,但是在葡萄牙语中使用特殊字符时遇到了问题。 I'm using the following code to return the file: 我正在使用以下代码返回文件:

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");
}

I'm setting utf8 as the encoding, but when a save the file and try to open it in Excel, I see junk characters instead of the special ones. 我将utf8设置为编码,但是当保存文件并尝试在Excel中打开文件时,我看到的是垃圾字符,而不是特殊字符。

If I just open the file in notepad and save it, then open it again on excel, is show the characters correctly. 如果我只是在记事本中打开文件并保存,然后在excel上再次将其打开,则可以正确显示字符。 Am I missing something to output the file as UTF8? 我是否缺少将文件输出为UTF8的内容?

The problem is Excel expects BOM. 问题是Excel需要BOM。 From this SO answer : 这个SO答案

var data = Encoding.UTF8.GetBytes(fileContent);
var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
return File(result, "text/csv", "RelMatriculas.csv");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM