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

asp.net 导出到CSV文件乱码的问题

程序员文章站 2024-03-07 20:01:27
http://social.microsoft.com/forums/zh-cn/295/thread/14a833f5-95bf-48ef-b6cf-c6028f3385...

http://social.microsoft.com/forums/zh-cn/295/thread/14a833f5-95bf-48ef-b6cf-c6028f338561

string name = system.configuration.configurationsettings.appsettings["downloadurl"].tostring();
filestream fs = new filestream(name, filemode.create, fileaccess.write);
streamwriter sw = new streamwriter(fs, system.text.encoding.getencoding("gb2312"));

sw.writeline(" 自动编号,姓名,年龄");
foreach (datarow dr in dt.rows)
{
sw.writeline(dr["id"] + "," + dr["vname"] + "," + dr["iage"]);
}
sw.close();
response.addheader("content-disposition", "attachment; filename=" + server.urlencode(name));
response.contenttype = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
response.writefile(name); // 把文件流发送到客户端
response.end();

重点为红色标记处!

------

string strfile = "filename" + datetime.now.tostring("yyyymmddhhmmss") + ".csv";

//这一部分替换为你从datatable/gridview获取的内容
stringbuilder sb = new stringbuilder();
sb.appendline("id,name");
sb.appendline("1,邹俊才");
sb.appendline("2,才俊邹");
sb.appendline("3,jon");

stringwriter sw = new stringwriter(sb);
sw.close();

response.addheader("content-disposition", string.format("attachment;filename={0}", strfile));
response.charset = "gb2312";
response.contenttype = "application/ms-excel";
response.contentencoding = system.text.encoding.getencoding("gb2312");
response.write(sw);
response.flush();
response.end();