用我转载的上一篇文章 Asp.net中把DataTable或DataGrid导出为Excel 导出的文档,中文有乱码现象,
其实要解决中文乱码很简单,设置一下字符集。如下:
- // 设置编码和附件格式
- curContext.Response.ContentType = "application/vnd.ms-excel";
- curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
- curContext.Response.Charset = "gb2312";
// 设置编码和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); curContext.Response.Charset = "gb2312";
另外,在输出的时候,最好加上以下语句:
<meta http-equiv="content-type" content="application/ms-excel; charset=gb2312"/>
- // 返回客户端
- dgExport.RenderControl(htmlWriter);
- curContext.Response.Clear();
- curContext.Response.Write("<meta http-equiv="content-type" content="application/ms-excel; charset=gb2312"/>" + strWriter.ToString());
- curContext.Response.End();
// 返回客户端 dgExport.RenderControl(htmlWriter); curContext.Response.Clear(); curContext.Response.Write("<meta http-equiv="content-type" content="application/ms-excel; charset=gb2312"/>" + strWriter.ToString()); curContext.Response.End();
完整方法如下: