本文面对的是第一次 接触NPOI的童鞋
不必为了一些琐碎的事情搞的心情烦躁
废话不多说先上 Demo 的全家福
接下来直接上代码
1 public partial class _Default : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 if (IsPostBack) 6 { 7 //导出Excel 8 ExportByWeb("ExportDemo.xlsx"); 9 } 10 RepeaterTable.DataSource = GetDtTable(); 11 RepeaterTable.DataBind(); 12 } 13 14 public static MemoryStream ExcelStream() 15 { 16 DataTable dtTable = GetDtTable(); 17 return ExcelHelper.ExportDT(dtTable, "HeaderText"); 18 19 } 20 21 private static DataTable GetDtTable() 22 { 23 string path = HttpContext.Current.Request.MapPath("~/App_Data/excel2007.xlsx"); 24 //调用ZK的ExcelHelper 25 DataTable dtTable = ExcelHelper.ImportExceltoDt(path); 26 return dtTable; 27 } 28 29 public static void ExportByWeb(string strFileName) 30 { 31 HttpContext curContext = HttpContext.Current; 32 33 // 设置编码和附件格式 34 curContext.Response.ContentType = "application/vnd.ms-excel"; 35 curContext.Response.ContentEncoding = Encoding.UTF8; 36 curContext.Response.Charset = ""; 37 curContext.Response.AppendHeader("Content-Disposition", 38 "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); 39 40 curContext.Response.BinaryWrite(ExcelStream().GetBuffer()); 41 curContext.Response.End(); 42 } 43 }
代码很简单,很容易看懂O(∩_∩)O~
前台绑定数据的代码
1 <h2> 2 欢迎使用 NPOI 3 </h2> 4 <asp:Repeater ID="RepeaterTable" runat="server"> 5 <HeaderTemplate> 6 <table border="1" cellpadding="10" cellspacing="0"> 7 <tr> 8 <td> 9 ID 10 </td> 11 <td> 12 品牌 13 </td> 14 <td> 15 型号 16 </td> 17 </tr> 18 </HeaderTemplate> 19 <ItemTemplate> 20 <tr> 21 <td> 22 <%# DataBinder.Eval(Container.DataItem,"ID") %> 23 </td> 24 <td> 25 <%# DataBinder.Eval(Container.DataItem,"品牌") %> 26 </td> 27 <td> 28 <%# DataBinder.Eval(Container.DataItem,"型号") %> 29 </td> 30 </tr> 31 </ItemTemplate> 32 <FooterTemplate> 33 </table> 34 </FooterTemplate> 35 </asp:Repeater> 36 <p> 37 <form action="/" method="post"> 38 <input type="submit" name="name" value="导出" /> 39 </form> 40 </p>
执行结果:
代码的下载地址
http://files.cnblogs.com/zhaozhengyan/ExcelDemoFor2.0.1.rar