C#将网页数据导出Excel时编码设置

 1         public void DGToExcel()
 2         {
 3             Response.ClearContent();
 4             Response.Charset = "GB2312";//内容编码
 5             Response.ContentType = "application/ms-excel";
 6             Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//内容编码
 7             Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("维修零件汇总" + System.DateTime.Now.ToShortDateString(), System.Text.Encoding.GetEncoding("UTF-8")) + ".xls");//导出文件名编码
 8             System.IO.StringWriter sw = new System.IO.StringWriter();
 9             HtmlTextWriter htw = new HtmlTextWriter(sw);
10             Gri_ViewSumFeeByYG.RenderControl(htw);
11             Response.Write(GetGridTableHtml(Gri_ViewSumFeeByYG));//将数据源按HTML格式写出
12             Response.End();
13         }
View Code

一般来讲,excel导出的文字编码只要两种就可以了:GB2312、UTF-8。

如果导出时出现乱码,可是尝试一下用别的编码。

另外值得注意的是,各个浏览器的兼容不一样,有可能在IE导出是文件名不是乱码,但是在火狐上面导出文件名就是乱码了。

原文地址:https://www.cnblogs.com/work-at-home-helloworld/p/ExportExcel.html