asp.net导出Excel乱码的原因及解决方法
程序员文章站
2024-02-24 14:26:22
复制代码 代码如下: protected void excel_click(object sender, eventargs e) { response.charset =...
复制代码 代码如下:
protected void excel_click(object sender, eventargs e)
{
response.charset = "utf-8";
response.clearcontent();
response.clear();
response.contentencoding = system.text.encoding.utf8;
response.headerencoding = system.text.encoding.utf8;
response.addheader("content-disposition", "attachment; filename=myexpress.xls");
response.contenttype = "application/excel";
system.io.stringwriter sw = new system.io.stringwriter();
htmltextwriter htw = new htmltextwriter(sw);
// turn off paging
gridview1.allowpaging = false;
databind();
gridview1.rendercontrol(htw);
response.write(sw.tostring());
response.end();
// turn the paging on again
gridview1.allowpaging = true;
databind();
}
关键:
复制代码 代码如下:
response.charset = "utf-8";//添加编码格式
response.clearcontent();
response.clear();
response.contentencoding = system.text.encoding.utf8;//表格内容添加编码格式
response.headerencoding = system.text.encoding.utf8;//表头添加编码格式
上边如果解决不了还可以用
复制代码 代码如下:
response.clearcontent();
response.clear();
response.addheader("content-disposition", "attachment; filename=sumlate.xls");
response.charset = "gb2312";
response.contentencoding = system.text.encoding.getencoding("gb2312");
response.contenttype = "application/excel";
system.io.stringwriter sw = new system.io.stringwriter();
htmltextwriter htw = new htmltextwriter(sw);
if (gridview2.rows.count > 0)
{
gridview2.rendercontrol(htw);
}
else
{
gridview1.rendercontrol(htw);
}
response.write(sw.tostring());
response.end();
关键:
复制代码 代码如下:
response.charset = "gb2312";
response.contentencoding = system.text.encoding.getencoding("gb2312");
注意观察,主要原因其实就是编码格式问题。
现在就能防止导出时候乱码问题了
上一篇: Python 学习之路-04 函数
下一篇: java自定义类加载器代码示例