程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net 導出到CSV文件亂碼的問題

asp.net 導出到CSV文件亂碼的問題

編輯:ASP.NET基礎

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();

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved