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?

2

1 Answer 1

15

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.