Export html table to excel file encoding

I had the task of writing code to export an html table with headers in excel.

What I came up with is the serverSide code:

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

This works pretty well, but there are some utf-8 characters (Russian) that arent showing the correlation in the excel file.

Any ideas I can do with this?

thanks for the help

+4
source share
2 answers

Change the 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 sending my answer, I saw that you already figured out the same solution. The error message you see is explained here: A warning about the Excel 2007 extension when opening an Excel workbook from a website and, unfortunately, there is no way around it.

From the post:

A warning prompt "by design", but the interaction cancels the action and IE attempts to open the file again - a known issue under investigation for a future fix.

+6
source

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 fine except for a warning when opening an excel file. thjere is an error that the file has a different format than the extension. Can i get rid of this?

0
source

Source: https://habr.com/ru/post/1384612/


All Articles