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();一定要加上。

 

 

 

 

 

 

转载于:https://www.cnblogs.com/iken1991/p/3715676.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值