导出为CSV转& " < > '字符为ascii

时间:2016-06-27 17:46:44

标签: c# asp.net excel csv

我的网页上有一个按钮,允许用户将数据表导出为CSV,以便在Excel中打开。问题是表格中的某些条目(特别是' comments'列)包含特殊字符。当我导出并在Excel中打开数据时,标题中列出的字符将转换为ASCII。我的代码中是否有任何地方可以阻止这种情况发生,或者它是否必须是用户自己处理的事情? 以下是导出功能:

 public void ExportToCSV(object sender, EventArgs e)
    {
        StringBuilder builder = new StringBuilder();
        string strFileName = "GridViewExcel_" + DateTime.Now.ToShortDateString() + ".csv";
        builder.Append("Date,High,Low,Average,Freeze Index, Sum FI, Thaw Index, Sum TI,Conditions, Comments" + Environment.NewLine);
        foreach (GridViewRow row in GridView1.Rows)
        {
            string date = "=" + "\"" + row.Cells[0].Text + "\"";
            string high = row.Cells[1].Text;
            string low = row.Cells[2].Text;
            string average = row.Cells[3].Text;
            string fi = row.Cells[4].Text;
            string sumfi = row.Cells[5].Text;
            string ti = row.Cells[6].Text;
            string sumti = row.Cells[7].Text;
            string conditions = "\"" + row.Cells[8].Text + "\"";
            string comments = "\"" + row.Cells[9].Text + "\"";
            builder.Append(date + "," + high + "," + low + "," + average + "," + fi + "," + sumfi + "," + ti + "," + sumti + "," + conditions + "," + comments + Environment.NewLine);
        }
        Response.Clear();
        Response.ContentType = "text/csv";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
        Response.Write(builder.ToString());
        Response.End();
    }

2 个答案:

答案 0 :(得分:0)

试试这个

    Response.Clear();
    Response.ContentType = "text/csv";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);

    Response.ContentEncoding = Encoding.Unicode;
    Response.BinaryWrite(Encoding.Unicode.GetPreamble());

    Response.Write(builder.ToString());
    Response.End();

答案 1 :(得分:0)

数据在GridView中编码,以便它可以在页面上正确显示。为了正确使用CSV的数据,您需要对其进行解码。

您可以使用HttpServerUtility.HtmlDecode方法执行此操作

var comments = $"\"{HttpServerUtility.HtmlDecode(row.Cells[9].Text)}\""