Ive got task to write code to export html table with headers to excel.
What I came up with is serverSide code like this:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=myexcel.xls");
Response.ContentType = "application/ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
tbPanel.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
It works quite well but there are some utf-8 characters (russian language) which arent displayed correclty in excel file.
Any ideas that can I do about it ?
Thanks for help
Change your code to the following:
Response.Clear();
Response.AddHeader("content-disposition","attachment;filename=myexcel.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();
Edit
While I was posting my answer, I saw that you already figured out the same solution. The error message that you're seeing is explained here: Excel 2007 Extension Warning On Opening Excel Workbook from a Web Site and, unfortunately, there is no way to workaround it.
From the post:
The alert prompt is "by design", but the interaction of the cancel action and IE's attempt to open the file again is a known problem under investigation for a future fix.
Ive added:
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());
And now it works ok except there is an warning while opening excel file thjere is an error that the file has got different format than the extension. Can I get Rid of that ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.