Reputation: 3305
How to decode HTML to CSV with user default encoding? Every Response.ContentEncoding I use exports gibberish.
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("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush()
Response.End();
SQL_Latin1_General_CP1_CI_AS data is displayed correctly as "Windows CP-1250" in Grid, however the CSV contains all the HTML encoded characters (ó
instead of ó
etc., same as in HTML source of grid). I'm totally lost with this encoding right now...
Upvotes: 0
Views: 1215
Reputation: 91510
The special characters you are seeing are not content encoded, they are HTML encoded. You need to HTML decode the string first.
Try changing:
Response.Output.Write(sb.ToString());
to
Response.Output.Write(HttpUtility.HtmlDecode(sb.ToString()));
Be aware that you might want to do this line-by-line for very large strings
(i.e. HTML decode the CSV out line by line):
sb.Append(HttpUtility.HtmlDecode(GridView1.Rows[i].Cells[k].Text) + ';');
Upvotes: 1