Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 €: 4 Dieselverbrauch in €: 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?

like image 850
theSpyCry Avatar asked Nov 05 '09 10:11

theSpyCry


3 Answers

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(); 
like image 149
theSpyCry Avatar answered Oct 22 '22 23:10

theSpyCry


Have you tried setting the encoding in a meta tag in the HTML?

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

Excel won't see the response headers, so it won't know what the Response.Encoding is. The meta tag allows it to find out.

like image 21
kͩeͣmͮpͥ ͩ Avatar answered Oct 22 '22 23:10

kͩeͣmͮpͥ ͩ


For instances where UTF8 is needed...

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);
like image 11
Franz Avatar answered Oct 22 '22 21:10

Franz