ASP.NET Excel导出编码问题

时间:2009-11-05 10:31:15

标签: asp.net encoding character-encoding

我正在ASP.NET站点上进行一些Excel导出。 除了编码之外,一切都有效。当我在Excel中打开它时,它看起来像这样:

  

Eingabe KostenjeGerätGerät:   Gerätebezeichnung:   BetrbsmittelHeizölinâ€:4   Dieselverbrauchinâ€:4

这是我的代码:

Response.Clear();
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename=NachkalkGeraete.xls;");
var writer = new HtmlTextWriter(Response.Output);

SomeControl.RenderControl(writer); /* FormView, Table, DataGrid... */

Response.End();

我已经尝试过显式设置编码..但没有发生任何变化:

Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=NachkalkGeraete.xls");

Response.BufferOutput = true;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Charset = "UTF-8";
EnableViewState = false;

System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);

SomeControl.RenderControl(hw);

Response.Write(tw.ToString());
Response.End();

出了什么问题?

6 个答案:

答案 0 :(得分:121)

我发现问题可能出在excel文件的标题中,它不包含 BOM字节序列(在表示所用编码的文件的开头)。 / p>

所以我这样做了,它对我有用:

Response.Clear();
Response.AddHeader("content-disposition","attachment;filename=Test.xls");   
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);

FormView1.RenderControl(hw);

Response.Write(sw.ToString());
Response.End(); 

答案 1 :(得分:11)

您是否尝试在HTML中的元标记中设置编码?

<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />

Excel不会看到响应标头,因此它不会知道Response.Encoding是什么。元标记允许它找出。

答案 2 :(得分:11)

对于需要UTF8的情况......

FileInfo dataExportFile = new FileInfo(dsExport.Tables[0].Rows[0]["DataExportFile"].ToString());

Response.Clear();
Response.ContentType = "application/ms-excel";                        
Response.AddHeader("Content-Disposition", "attachment;filename=" + dataExportFile.Name);
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.TransmitFile(dataExportFile.FullName);

答案 3 :(得分:3)

我对西班牙语字符有同样的问题并用这行代码解决了。

        response.ContentEncoding = System.Text.Encoding.Default ;

希望这会有所帮助

答案 4 :(得分:2)

添加 Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

答案 5 :(得分:1)

您可以尝试使用“Server.HtmlDecode”来解码像“João”这样的单词

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e){
String wrong = "Jo&#227;o";
String corrected = Server.HtmlDecode(wrong);}