ASP.NET简易导出Excel

时间:2014-05-08 18:16:51   收藏:0   阅读:276

使用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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!