asp.net将控件或页面数据导出到Excel

利用Response.ContentType 属性,设置为application/vnd.ms-excel,将文本数据以microsoft excel的格式输出(Response)到客户端。

如,导出DataGrid:

 1 //要导出的DataGrid控件  
 2 
 3 protected void Button2_Click(object sender, EventArgs e)  
 4 
 5     {  
 6 
 7         //要导出的控件  
 8 
 9         System.Web.UI.Control ctl = this.Label1;  
10 
11    
12 
13         //输出属性  
14 
15         HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");  
16 
17         HttpContext.Current.Response.Charset = "UTF-8";  
18 
19         HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;  
20 
21         HttpContext.Current.Response.ContentType = "application/ms-excel";  
22 
23    
24 
25         //输出空间内容到HtmlTextWriter  
26 
27         ctl.Page.EnableViewState = false;  
28 
29         System.IO.StringWriter tw = new System.IO.StringWriter();  
30 
31         System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);  
32 
33         ctl.RenderControl(hw);  
34 
35    
36 
37         //输出HtmlTextWriter  
38 
39         HttpContext.Current.Response.Write(tw.ToString());  
40 
41         HttpContext.Current.Response.End();  
42 
43     } 

使用这种方法,可以将大部分控件的数据都导入到Excel文件中。如Literal、GridView、Repeater、Label,只要这些控件中的数据是格式良好的表格,导出的Excel格式也是以表格数据形式展现。

将上边的代码直接写入到Page_Load中,可以将整个页面下载为Excel文件.

 1 protected void Page_Load(object sender, EventArgs e)  
 2 
 3     {  
 4 
 5         if (!IsPostBack)  
 6 
 7         {  
 8 
 9             Response.Clear();  
10 
11             Response.Buffer = true;  
12 
13             Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls");  
14 
15             Response.ContentEncoding = System.Text.Encoding.UTF8;  
16 
17             Response.ContentType = "application/vnd.ms-excel";  
18 
19             this.EnableViewState = false;  
20 
21         }  
22 
23     } 
原文地址:https://www.cnblogs.com/gates/p/3124318.html