如何使用用户默认编码将HTML解码为CSV?每个Response.ContentEncoding我都使用导出乱码。
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();
网格到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("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush()
Response.End();
SQL_Latin1_General_CP1_CI_AS数据在网格中正确显示为“Windows CP-1250”,但CSV包含所有HTML编码字符(ó
而不是ó
等,与网格的HTML源相同)。我现在完全失去了这种编码......
答案 0 :(得分:1)
您看到的特殊字符不是内容编码的,而是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) + ';');