首先,这是我的代码:
DataTable usersReport = reportsService.GenerateUsersReport();
var grid = new GridView();
grid.DataSource = usersReport;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=UsersReport.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
正如您所看到的,我只是以简单的方式生成有关用户的报告。当我在excel中打开此文件时,特殊字符存在问题,例如ś,ż,ź,ó,ę,ą
等。
而不是Imię
我可以看到ImiÄ™
。
与GyżyÅ„ski
我该如何解决?
编辑:
添加以下行:
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
现在Imię
看起来像Imiê
。总之 - 仍然没有
答案 0 :(得分:0)
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=UsersReport.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
答案 1 :(得分:0)
经过一番调查后,我发现了一个解决方案。重要的是源HTML的<meta>
标记。
这样一行:
Response.Output.Write(sw.ToString());
应如下所示:
Response.Output.Write("<meta http-equiv='Content-Type' content='application/vnd.ms-excel; charset=utf-8'>" + sw.ToString());
答案 2 :(得分:0)
以下代码将对特殊字符使用Wrk并将Excel中的null删除为 从数据表中,我们正在创建同时写入特殊字符的Excel
主要技巧是使其成为UTF-32并应用BinaryWrite
public void DataTableToExcel(DataTable dt)
{
string attachment = "attachment; filename=download.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentEncoding = System.Text.Encoding.UTF32;
Response.BinaryWrite(System.Text.Encoding.UTF32.GetPreamble());
Response.ContentType = "application/vnd.xls";
string tab = "";
foreach (DataColumn dc in dt.Columns) // table col
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
string content = "";
foreach (DataRow dr in dt.Rows) // Data Row by row
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
content = dr[i].ToString();
content = content.Replace(System.Environment.NewLine, " ");
Response.Write(tab + content);
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}