I'm trying to implement a simple data import to my MVC application from .csv file.
To remove the need for user to save .csv file template in his computer and from going through the trouble of getting it in the first place, I created a button on my form that generates the template.
I generate a string from my model object in a writer class:
this.Writer.GetCswTemplate()
returns string from viewModel (i.e. column1;colum2\r\n)
As per How to GetBytes() in C# with UTF8 encoding with BOM?
I force excel to open .csv file with UTF-8 encoding:
var templateResult = Encoding.UTF8.GetBytes(this.Writer.GetCswTemplate());
var preamble = Encoding.UTF8.GetPreamble();
var templateBytes = preamble.Concat(templateResult).ToArray();
to send the generated template to the user I use MVC File() helper:
return this.File(templateBytes, "application/csv", "filename.csv");
It works great, it generates the template, returns it to the user, opens it with Excel and shows all the special characters in it. If I open the generated file in Notepad++ I can see that it's encoding is UTF-8.
The problem occurs when a user fills the generated template and saves it inside Excel. For some reason Excel decides to change file encoding to ANSI.
Is there any way for me to prevent that? Did I miss something (Add some kind of header or something)?
Interestingly if I generate template with UTF-8 (without BOM), modify said file in excel and save it, Excel does not change its encoding to ANSI. The problem then is that Excel does not recognize the special characters inside template.