3

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?

Tetsuya Yamamoto
  • 23,159
  • 5
  • 39
  • 56
Marlon
  • 1,449
  • 2
  • 18
  • 33

1 Answers1

10

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");
Magnetron
  • 6,121
  • 1
  • 20
  • 38