如何解码HTML到CSV与用户默认编码?每一个响应。我使用导出乱码
SQL to Grid:SqlConnection conn = new SqlConnection(connectionString);
string select = "SELECT...";
SqlDataAdapter DataCommand = new SqlDataAdapter(select, conn);
DataSet ds = new DataSet();
DataCommand.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
Grid to CSV:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=CSVfile.csv");
Response.ContentType = "text/csv";
// other encoding like utf-8 also exports encoded data
Response.ContentEncoding = Encoding.GetEncoding("Windows-1250");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Rows[0].Cells.Count; k++)
{
sb.Append(GridView1.Rows[i].Cells[k].Text + ';');
}
sb.Append("rn");
}
Response.Output.Write(sb.ToString());
Response.Flush()
Response.End();
SQL_Latin1_General_CP1_CI_AS数据在Grid中正确显示为"Windows CP-1250",但是CSV包含所有HTML编码字符(ó
而不是ó
等,与HTML source of Grid相同)。我完全失去了这个编码现在…
您看到的特殊字符不是内容编码,而是HTML编码。您需要先对字符串进行HTML解码。
尝试改变:
Response.Output.Write(sb.ToString());
Response.Output.Write(HttpUtility.HtmlDecode(sb.ToString()));
请注意,对于非常大的字符串
,您可能需要逐行执行此操作。(即。HTML解码CSV逐行输出):
sb.Append(HttpUtility.HtmlDecode(GridView1.Rows[i].Cells[k].Text) + ';');