Chinese characters appearing incorrectly in Excel when generated by an ASP.Net page

We recently launched a site that required an excel download to be generated with complex and simplified Chinese characters. In producing this we had issues presenting the Chinese – they would come out as garbage. It was strange as if you saved in notepad and re-opened in excel it would be fine, so the problem looked to lie with Excels handling of Unicode. After trying various encoding combinations, without luck we found that the stream required a byte leader to let excel know it was about to receive Unicode.

string attachment = “attachment; filename=Inventory” + DateTime.Now.Month + “-” + DateTime.Now.Year + “.xls”;
string filename = “Inventory” + DateTime.Now.Month + ” – ” + DateTime.Now.Year + “.xls”;
HttpContext.Current.Response.ContentType = “application/”;
HttpContext.Current.Response.ContentEncoding = Encoding.Unicode;
HttpContext.Current.Response.AddHeader(“content-disposition”, attachment);

‘this is the key part of the fix

var b = Encoding.Unicode.GetPreamble();
//Write your code here to write the file
// i.e. HttpContext.Current.Response.Write(“column1, column2, column3”);

hope this helps, as it took as while to figure this out.


Leave a Reply

Your email address will not be published. Required fields are marked *