通过跟踪Asp.net服务器代码,没有乱码,然而导出Excel到浏览器后,打开时出现乱码。
解决方法是添加编码格式的前缀字节码:
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
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();
例如Utf-8的Preamble是3个字节:239,187,191。这三个字节位于文件的头部,表示我们的文件是utf-8格式的。