zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

Net文件ASP导出 问题 乱码 csv
2023-06-13 09:14:17 时间

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

stringname=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString();
FileStreamfs=newFileStream(name,FileMode.Create,FileAccess.Write);
StreamWritersw=newStreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));

sw.WriteLine("自动编号,姓名,年龄");
foreach(DataRowdrindt.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();

重点为红色标记处!

------

stringstrFile="FileName"+DateTime.Now.ToString("yyyyMMddhhmmss")+".csv";

//这一部分替换为你从DataTable/GridView获取的内容
StringBuildersb=newStringBuilder();
sb.AppendLine("id,name");
sb.AppendLine("1,邹俊才");
sb.AppendLine("2,才俊邹");
sb.AppendLine("3,Jon");

StringWritersw=newStringWriter(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();