5

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
  • 24,297
  • 8
  • 39
  • 61
Marlon
  • 1,719
  • 3
  • 20
  • 42

1 Answers1

14

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
  • 7,495
  • 1
  • 25
  • 41