简介:NPOI是POI(APATCH的一个开源项目)项目的.NET版本,最初的POI只用于JAVA来操作EXCEL or WORD等微软OLE2组件项目。使用NPOI可以完成在你没有安装Office或者相应环境的机器上对WORD/EXCEL文档进行读写。
使用案例分享(NPOI针对DATATABLE导出EXCEL):
完成此任务应该准备的DLL:NPOI.DLL ,官网下载链接:http://npoi.codeplex.com/
1.将npoi.dll引用到项目的bin目录中:
2.添加完成之后,代码例子开始:
(对于这种以后项目里可能会经常使用到的工具类,本人建议直接创建一个公共的Respository,相信你懂我的用意)
这里我创建了一个ExcelHelper.cs类,其中需要引用以下几个npoi相关的namespace
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel;
导出的测试代码:(经过测试,可正常使用,这个方法需要优化的地方挺多,有兴趣的话可以自己拿去改善)
1 public static void TableToExcelForXLS(DataTable dt, string file,string entityName) //dt:你需要导出的数据,file:导出路径,entityName:实体名称 2 { 3 HSSFWorkbook hssfworkbook = new HSSFWorkbook(); 4 ISheet sheet = hssfworkbook.CreateSheet("Test"); 5 6 //表头 7 IRow row = sheet.CreateRow(0); 8 //for (int i = 0; i < dt.Columns.Count; i++) 9 //{ 10 string[] str = { "a", "b", "c", "d", "e", "f" }; 11 string[] sysSelect = {"A", "B", "C", "D"}; 12 if (entityName == "XuDaxia") 13 { 14 //表头 15 for (int j = 0; j < str.Count(); j++) 16 { 17 ICell cell = row.CreateCell(j); 18 cell.SetCellValue(str[j]); 19 } 20 //数据 21 for (int i = 0; i < dt.Rows.Count; i++) 22 { 23 IRow row1 = sheet.CreateRow(i + 1); 24 for (int j = 0; j < dt.Columns.Count; j++) 25 { 26 ICell cell = row1.CreateCell(j); 27 cell.SetCellValue(dt.Rows[i][j].ToString()); 28 } 29 } 30 } 31 else 32 { 33 //表头 34 for (int j = 0; j < sysSelect.Count(); j++) 35 { 36 ICell cell = row.CreateCell(j); 37 cell.SetCellValue(sysSelect[j]); 38 } 39 //数据 40 for (int i = 0; i < dt.Rows.Count; i++) 41 { 42 IRow row1 = sheet.CreateRow(i + 1); 43 for (int j = 0; j < dt.Columns.Count; j++) 44 { 45 ICell cell = row1.CreateCell(j); 46 cell.SetCellValue(dt.Rows[i][j].ToString()); 47 } 48 } 49 } 50
方法调用:
1 protected void btn_ExportExcel(object sender, ImageClickEventArgs e) 2 { 3 var name = DateTime.Now.ToString("yyyyMMdd") + new Random(DateTime.Now.Second).Next(10000);//导出的Excel默认名称 4 var path = Server.MapPath("XUDAXIA_TEST/" + name + ".xls");//导出路径 5 var dt = list.ToDataTable(); 6 string ef= "Xudaxia"; 7 ExcelHelper.x2003.TableToExcelForXLS(dt, path, ef); //2003 版Excel示例 8 downloadfile(path); 9 }
输出参数配置:
void downloadfile(string s_path) { System.IO.FileInfo file = new System.IO.FileInfo(s_path); HttpContext.Current.Response.ContentType = "application/ms-download"; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream"); HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8)); HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString()); HttpContext.Current.Response.WriteFile(file.FullName); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.End(); }