Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

ASP.NET Excel export encoding problem

I'm doing some Excel Exports on the ASP.NET Site. Everything works except of the Encoding. When I open it in Excel, it looks like this:

Eingabe Kosten je Ger?¤t Ger?¤t: Ger?¤tebezeichnung: Betriebsmittel Heiz??l in a??: 4 Dieselverbrauch in a??: 4

This is my code:

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

I've already tried explicitly set the Encoding.. but no change occured:

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

What is wrong, please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well I found out that the problem could be in the header of the excel file, that it does not contain the BOM byte sequence (at the beginning of the file representing the encoding used).

So I made it this way and it works for me:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...