asp.net中将GridView数据导出成Excel文件(下)

asp.net中将GridView数据导出成Excel文件(下)

/// 导出GridView中的数据到Excel
private static void GoToExcel ( GridView gvw , string title )
{
string fileName ;
HttpContext . Current . Response . Buffer = true ;
HttpContext . Current . Response . ClearContent ();
HttpContext . Current . Response . ClearHeaders ();
fileName = string . Format ( "Export-File {0:yyyy-MM-dd_HH_mm}.xls" , DateTime . Now ); //生成导出文件名
HttpContext . Current . Response . AppendHeader ( "Content-Disposition" , "attachment;filename=" + fileName ); //关联要生成的文件
HttpContext . Current . Response . ContentType = "application/vnd.ms-excel" ;
StringWriter tw = new System . IO . StringWriter (); //创建StringWriter对象实例
HtmlTextWriter hw = new System . Web . UI . HtmlTextWriter ( tw );

//根据StringWriter对象创建HtmlTextWriter对象实例
gvw.RenderControl(hw); //将GridView内输入HtmlTextWriter中,并跟踪信息
if (!string.IsNullOrEmpty(title)) //如果 title 不为空则加入title内容
{
HttpContext.Current.Response.Write("<b><center><font size=3 face=Verdana color=#0000FF>" +title +"</font></center></b>"); }
HttpContext.Current.Response.Write(tw.ToString()); //正真写入内容到文件
 
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
gvw.Dispose(); //释放过程中的对象实例
tw.Dispose();
hw.Dispose();
gvw = null;
tw = null;
hw = null;
}

}
}

调用示例:
List orders=this. GetOrders
(); // 得到ist数据
ToExcel
.ExportToExcel(orders,
new string[] { "OrderNo", "CustomerNo", "UserNo", "ModelNo","Quantity","Price","Amount","OrderDate" },
new string[] { "订单","客户代码","用户代码","型号","数量","价格","金额","订货日期"}
);

http://blog.sina.com.cn/s/blog_4d174ff90100i4dd.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值