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