导出为CSV将“<>”字符变成ascii

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

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

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

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

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

尝试这个

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