欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net导出Excel乱码的原因及解决方法

程序员文章站 2024-02-27 12:19:03
复制代码 代码如下: 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");

注意观察,主要原因其实就是编码格式问题。

现在就能防止导出时候乱码问题了