如何对csv导出进行HTML编码

时间:2011-06-22 18:46:52

标签: c# html asp.net csv

我得到了

 Quattrode® 

从HTML编码为

的字符串
Quattrode® 

在Excel 2007中查看时。

例程

        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, ","));

基本上DataGridToCSV()使用HttpUtility.HtmlDecode(stringBuilder.ToString());,我可以使用visual studio的文本可视化工具,看看字符串看起来是否正确(Quattrode®)。

因此Response过程或Excel对文件的解释中的某些内容不正确。知道怎么解决吗?

<小时/> 的更新
事实证明,这在Excel或写字板中无法正确解释。我在记事本中打开它,符号显示正确。

3 个答案:

答案 0 :(得分:8)

我在这里找到了答案https://stackoverflow.com/a/3300854/150342 在这里https://stackoverflow.com/a/6460488/150342 然后汇总这段代码:

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

答案 1 :(得分:5)

也试试这个

Response.ContentEncoding = Encoding.UTF32;

答案 2 :(得分:1)

Response.Charset =“”;

尝试使用UTF-8

之类的东西