Reputation: 44285
I get
Quattrode®
From a string that is HTML encoded as
Quattrode®
when viewing inside Excel 2007.
Routine
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/comma-separated-values";
Response.AddHeader("Content-Disposition", "attachment;filename=\"Expired.csv\"");
Response.RedirectLocation = "export.csv";
Response.Charset = "";
//Response.Charset = "UTF-8";//this does not work either.
EnableViewState = false;
ExportUtility util = new ExportUtility();
Response.Write(util.DataGridToCSV(gridViewExport, ","));
Basically DataGridToCSV()
uses HttpUtility.HtmlDecode(stringBuilder.ToString());
and I can use visual studio's text visualizer and see the string looks correct (Quattrode®).
So something in the Response
procedure or in Excel's interpretation of the file is not correct. Any idea how to fix?
Upvotes: 2
Views: 8119
Reputation: 22595
I found the answer here https://stackoverflow.com/a/3300854/150342 and here https://stackoverflow.com/a/6460488/150342 Then put together this code:
public static void WriteCSVToResponse(string csv, string filename)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.ContentType = "text/csv";
response.AddHeader("content-disposition", "attachment; filename=" + filename);
response.ContentEncoding = Encoding.UTF8;
byte[] BOM = new byte[] { 0xef, 0xbb, 0xbf };
response.BinaryWrite(BOM);//write the BOM first
response.BinaryWrite(Encoding.UTF8.GetBytes(csv));
response.Flush();
response.End();
}
Upvotes: 8