ASP.NET简易导出Excel
使用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();一定要加上。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。