使用NPOI实现简单的Excel导出功能
【1】NPOI
NPOI是指构建在POI 3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。
使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。
(哈哈,我不会告诉你这一段是从百度百科copy过来的~~)
【2】实例操作
我其实也没怎么深入研究,因为最近的MVC项目里目前只需要Excel导出的功能,所以就只尝试了这一种,所幸成功了,但是也借鉴了很多网上博客分享的知识,都是一知半解,最后还是向公司前辈们讨教了一下,就提供给我了一个他们封装好的帮助类。
这样的好东西自然是要拿出来分享啦~经过公司前辈们的恩准,我才得以把这些代码贴出来,这边就做个勤劳的小搬运工好了(:-D)
下面就开始说明具体的一些实现过程:
首先,我们需要引用一些必要的程序集:(点我下载哦)
NPOI.dll
NPOI.POIFS.dll
NPOI.HSSF.dll
NPOI.Util.dll
蓝后,贴一个帮助类,包含List转换成DataTable方法以及将DataTable导出到Excel表格的方法:

1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Linq; 6 using NPOI.SS.UserModel; 7 using NPOI.XSSF.UserModel; 8 9 namespace NPOIExportDemo.Utility 10 { 11 /// <summary>实体转换辅助类</summary> 12 public class EntityConvertHelper<T> where T : class, new() 13 { 14 /// <summary>List转换成DataTable, 主键为自增长</summary> 15 /// <typeparam name="T">类型</typeparam> 16 /// <param name="value">List</param> 17 /// <returns>DataTable</returns> 18 public static DataTable ConvertToDataTable(List<T> value) 19 { 20 var properties = TypeDescriptor.GetProperties(typeof(T)); 21 var dataTable = new DataTable(); 22 for (var i = 0; i < properties.Count; i++) 23 { 24 var property = properties[i]; 25 dataTable.Columns.Add(property.Name, property.PropertyType); 26 } 27 var data = new object[properties.Count]; 28 value.ForEach(x => 29 { 30 for (var i = 0; i < data.Length; i++) 31 { 32 data[i] = properties[i].GetValue(x); 33 } 34 dataTable.Rows.Add(data); 35 }); 36 //移除PkValue列 37 if (dataTable.Columns.Contains("PkValue")) 38 { 39 dataTable.Columns.Remove("PkValue"); 40 } 41 return dataTable; 42 } 43 44 /// <summary>导出</summary> 45 /// <param name="list">List数据</param> 46 /// <param name="columnAndName">要导出的列名和表头名称字典(Key:列名,Value:表头名称)</param> 47 /// <returns>结果(使用时记得回收)</returns> 48 public static IWorkbook Export(List<T> list, Dictionary<string, string> columnAndName) 49 { 50 if (list == null || list.Count.Equals(0)) return null; 51 DataTable table = ConvertToDataTable(list); 52 var columnList = (from DataColumn column in table.Columns select column.ColumnName).ToList(); 53 var keyList = columnAndName.Keys.ToList(); 54 var outColumnList = keyList.Where(x => !columnList.Contains(x)).ToList(); 55 if (outColumnList.Count > 0) 56 { 57 throw new Exception("要导出的列名和表头名称字典包含DataTable所没有的列名"); 58 } 59 IWorkbook workbook = new XSSFWorkbook(); 60 ISheet sheet = workbook.CreateSheet(); 61 IRow headerRow = sheet.CreateRow(0); 62 List<string> headerTitle = columnAndName.Values.ToList(); 63 for (int index = 0; index < headerTitle.Count; index++) 64 { 65 headerRow.CreateCell(index).SetCellValue(headerTitle[index]); 66 } 67 int rowIndex = 1; 68 foreach (DataRow row in table.Rows) 69 { 70 IRow dataRow = sheet.CreateRow(rowIndex); 71 List<string> clounmContentList = new List<string>(); 72 foreach (var key in keyList) 73 { 74 clounmContentList.Add(row[key].ToString()); 75 } 76 for (int index = 0; index < clounmContentList.Count; index++) 77 { 78 dataRow.CreateCell(index).SetCellValue(clounmContentList[index]); 79 } 80 rowIndex++; 81 } 82 return workbook; 83 } 84 } 85 }
紧接着,我们就要在controller里面去调用它们啦~

1 using NPOIExportDemo.Utility; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Web; 6 using System.Web.Mvc; 7 8 namespace NPOIExportDemo.Controllers 9 { 10 public class NPOIDemoController : Controller 11 { 12 // GET: NPOIDemo 13 public ActionResult Index() 14 { 15 return View(); 16 } 17 18 19 public void Export() 20 { 21 List<Info> infos = new List<Info>() 22 { 23 new Info {Name = "Tomcat", Age = 10, Time = "2017-08-03 10:34:37"}, 24 new Info {Name = "Jerry", Age = 35, Time = "2017-08-03 10:34:37"}, 25 new Info {Name = "Mike", Age = 22, Time = "2017-08-03 10:34:37"}, 26 new Info {Name = "J.M", Age = 54, Time = "2017-08-03 10:34:37"}, 27 new Info {Name = "aaa", Age = 12345, Time = "2017-08-03 10:34:37"} 28 }; 29 Dictionary<string, string> dic = new Dictionary<string, string>() 30 { 31 {"Name", "姓名"}, 32 {"Age", "年龄"}, 33 {"Time", "时间"} 34 }; 35 try 36 { 37 using (MemoryStream ms = new MemoryStream()) 38 { 39 var workBook = EntityConvertHelper<Info>.Export(infos, dic); 40 workBook.Write(ms); 41 string filename = "报表导出" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".xlsx"; 42 if (Request.Browser.Browser == "IE") 43 filename = HttpUtility.UrlEncode(filename); 44 Response.Clear(); 45 Response.AddHeader("Content-Disposition", "attachment;fileName=" + filename); 46 Response.BinaryWrite(ms.ToArray()); 47 Response.End(); 48 } 49 } 50 catch (Exception e) 51 { 52 } 53 } 54 } 55 56 public class Info 57 { 58 public string Name { get; set; } 59 public int Age { get; set; } 60 public string Time { get; set; } 61 } 62 }
最后94页面啦~

1 <script src="~/scripts/jquery-1.12.3.js"></script> 2 3 <form action="/NPOIDemo/Export" method="post" id="exportform"> 4 <button type="submit">导出</button> 5 </form>
这个就很单纯的使用了一个form表单提交形式的按钮,其他应该也是可以的~
我的代码分享差不多就是这样,当然最牛的帮助类的代码都是前辈们提供给我的,在此向他们献上我的膝盖(扑通~)。
如果大家有什么疑问可以留言问我,或者觉得好用的话给点个赞,我好向亲爱的前辈们有个交代~
/****************************我是可爱的分割线*********************************/