简体   繁体   中英

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. 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.

If I just open the file in notepad and save it, then open it again on excel, is show the characters correctly. Am I missing something to output the file as UTF8?

The problem is Excel expects BOM. From this SO answer :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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