简体   繁体   中英

How to HTML encode a csv export

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?


UPDATE
Turns out that this is not interpreted properly in Excel or WordPad. I open it up in Notepad and the symbol shows up properly.

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();
    }

也试试这个

Response.ContentEncoding = Encoding.UTF32;

Response.Charset = "";

Try using something like UTF-8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM