I am using the technique from another stack overflow question to write a CSV file to the Response output for the user to open / save. The file looks good in Notepad, but when I open it in Excel, accented characters are garbage. I assumed that this had something to do with character encoding, so I tried to manually set it to UTF-8 (the default for StreamWriter ). Here is the code:
// This fills a list to enumerate - each record is one CSV line List<FullRegistrationInfo> fullUsers = GetFullUserRegistrations(); context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment; filename=registros.csv"); context.Response.ContentType = "text/csv"; context.Response.Charset = "utf-8"; using (StreamWriter writer = new StreamWriter(context.Response.OutputStream)) { for (int i = 0; i < fullUsers.Count(); i++) { // Get the record to process FullRegistrationInfo record = fullUsers[i]; // If it the first record then write header if (i == 0) writer.WriteLine(Encoding.UTF8.GetString( Encoding.UTF8.GetPreamble()) + "User, First Name, Surname"); writer.WriteLine(record.User + "," + record.FirstName + "," + record.Surname); } } context.Response.End();
Any ideas on what else I need to do to properly encode the file so that Excel can view accented characters?
source share