ASP.NET Excel导出编码问题

我在ASP.NET网站上做了一些Excel导出。 除了编码之外,一切都可以使用。 当我在Excel中打开它时,它看起来像这样:

Eingabe Kosten jeGerätGerät:Gerätebezeichnung:BetriebsmittelHeizöl在“4 Dieselverbrauch in: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(); 

请问有什么不对?

那么我发现问题可能在Excel文件的头部,它不包含BOM字节序列 (在代表所使用的编码的文件的开头)。

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

 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(); 

你有没有尝试在HTML元标记中设置编码?

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

Excel不会看到响应标题,所以它不会知道Response.Encoding是什么。 元标签允许它找出。

对于需要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); 

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

我得到西class牙字符相同的问题,并解决了这一行代码。

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

希望这可以帮助

您可以尝试使用“Server.HtmlDecode”解码这些单词,如“João”

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