使用asp.net导出Excel有多重方法。经过总结,现推荐一种简易方法,不用再记那些复杂的类名了。
code:
using System.Data;
using System.IO;
//add Microsoft.Excel refference and set operation right in server first
public void exportExcel(DataTable dt, string fileName)
{
StringWriter sw=new StringWriter();
foreach(DataRow row in dt.Rows)
{
sw.write(row[0]);
sw.write("\t"); //write a Excel cell
sw.writeLine(); //write another line
}
sw.Close();
System.Web.HttpContext.Current.Response.AddHeader("Content-Dispositon","Attachment;filename="+filename);
System.Web.HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
System.Web.HttpContext.Current.Response.ContentType="Application/ms-excel";
System.Web.HttpContext.Current.Response.Write(sw);
System.Web.HttpContext.Current.Response.End(); //this line of code must be added, or the Excel file will be empty
}
如果直接写在后台的话,System.Web.HttpContext.Current.Response直接写成Response就行了。注意最后一句Respond.End();一定要加上。
ASP.NET简易导出Excel,布布扣,bubuko.com
原文:http://www.cnblogs.com/iken1991/p/3715676.html