首页 > Web开发 > 详细

ASP.NET简易导出Excel

时间:2014-05-08 18:16:07      阅读:329      评论:0      收藏:0      [点我收藏+]

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

ASP.NET简易导出Excel

原文:http://www.cnblogs.com/iken1991/p/3715676.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!