C# 将数据导出到Excel汇总|C#导出Excel汇总

下载全部源代码,这里不再更新,请大家移步:   http://www.sufeinet.com/thread-4-1-1.html

一、asp.net中导出Excel的方法:

在asp.net中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上;一种是将文件直接将文件输出流写给浏览器。在Response输出时,t分隔的数据,导出Excel时,等价于分列,n等价于换行。
1、将整个html全部输出Excel

此法将html中所有的内容,如按钮,表格,图片等全部输出到Excel中。

   Response.Clear();     
 
   Response.Buffer=   true;     
 
   Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");           
 
   Response.ContentEncoding=System.Text.Encoding.UTF8;   
 
   Response.ContentType   =   "application/vnd.ms-excel";   
 
   this.EnableViewState   =   false;   

这里我们利用了ContentType属性,它默认的属性为text/html,这时将输出为超文本,即我们常见的网页格式到客户端,如果改为ms-excel将将输出excel格式,也就是说以电子表格的格式输出到客户端,这时浏览器将提示你下载保存。ContentType的属性还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我们也可以输出(导出)图片、word文档等。下面的方法,也均用了这个属性。

2、将DataGrid控件中的数据导出Excel

上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。而我们一般要导出的是数据,DataGrid控件上的数据。

  
 
System.Web.UI.Control ctl=this.DataGrid1;
 
//DataGrid1是你在窗体中拖放的控件
 
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls"); 
HttpContext.Current.Response.Charset ="UTF-8";     
 
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default; 
HttpContext.Current.Response.ContentType ="application/ms-excel";
 
ctl.Page.EnableViewState =false;    
System.IO.StringWriter  tw = new System.IO.StringWriter() ; 
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw); 
ctl.RenderControl(hw); 
HttpContext.Current.Response.Write(tw.ToString()); 
HttpContext.Current.Response.End(); 

 原文: http://www.sufeinet.com/thread-4-1-1.html

本人的博客不再维护从2013年就不再维护了 需要我帮助的朋友请到我的个人论坛 http://www.sufeinet.com 进行讨论,感谢大家对我的支持!
原文地址:https://www.cnblogs.com/sufei/p/1487540.html