export html table to excel file encoding

19,739

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.

Share:
19,739
gruber
Author by

gruber

Updated on August 22, 2022

Comments

  • gruber
    gruber over 1 year

    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

  • NakedBrunch
    NakedBrunch over 12 years
    I just posted the same answer but a bit too late. Glad you got it working. The error you're seeing is explained here: blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/…