数据导出成Excel
1、table里的数据导出成Excel runat="server"
View Code
1 protected void Btn_OutEXL_Click(object sender, EventArgs e) 2 3 { 4 5 bind_infor(); 6 7 string strDate1 = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); 8 9 Response.Charset = "GB2312"; 10 11 Response.ContentEncoding = System.Text.ASCIIEncoding.UTF8; 12 13 Response.ContentType = "application/ms-excel"; 14 15 Response.AppendHeader("Content-Disposition", "attachment;filename=工资统计表(" + strDate1.ToString() + ").xlsx"); 16 17 StringWriter tw = new StringWriter(); 18 19 HtmlTextWriter hw = new HtmlTextWriter(tw); 20 21 outEW.RenderControl(hw);//outEW为table的id 22 23 Response.Write(tw.ToString()); 24 25 Response.End(); 26 27 }
2、Repeater里的数据导出成Excel
首先,设置样式:
<HeaderTemplate >表头信息</HeaderTemplate >
<ItemTemplate>绑定信息</ItemTemplate>
<FooterTemplate>表尾信息</FooterTemplate>
导出按钮:
<asp:Button ID="Btn_OutEXL" runat="server" Text="导出xls"
onclick="Btn_OutEXL_Click" style="width: 100px; height: 30px;" />
后台代码:
View Code
1 protected void Btn_OutEXL_Click(object sender, EventArgs e) 2 3 { 4 5 bind_infor(); 6 7 string strDate1 = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); 8 9 base.Response.Clear(); 10 11 base.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 12 13 base.Response.AddHeader("content-disposition", "attachment;filename=工资统计表(" + strDate1.ToString() + ").xlsx"); 14 15 base.Response.Charset = "gb2312";//gb2312,utf-8,UTF7 16 17 //base.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); 18 19 //Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档 20 21 base.Response.ContentType = "application/vnd.xls"; 22 23 this.EnableViewState = false; 24 25 // 定义一个输入流 26 27 StringWriter writer = new StringWriter(); 28 29 HtmlTextWriter Htmlwriter = new HtmlTextWriter(writer); 30 31 this.Repeater1.RenderControl(Htmlwriter); 32 33 //this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件 34 35 base.Response.Write(writer.ToString()); 36 37 base.Response.End(); 38 39 }
天再高,踮起脚尖就能更接近阳光