P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

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.

Upvotes: 2

Views: 8119

Answers (3)

Colin
Colin

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

Aristos
Aristos

Reputation: 66641

Also try this

Response.ContentEncoding = Encoding.UTF32;

Upvotes: 5

BRampersad
BRampersad

Reputation: 862

Response.Charset = "";

Try using something like UTF-8

Upvotes: 1

Related Questions