利用NPOL,导出Excel
首先,需要在项目中添加NPOL引用,然后引用程序集进行代码编写,核心代码如下 ,由此可研究一下到处动态列表数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //生成excel 2 public static void RenderToExcel<T>(string title, IEnumerable<T> data, HttpContextBase context, string fileName) where T : class 3 { 4 using (MemoryStream ms = RenderToExcel(title, data)) 5 { 6 RenderToBrowser(ms, context, fileName); 7 } 8 } 9 //输出到浏览器 10 private static void RenderToBrowser(MemoryStream ms, HttpContextBase context, string fileName) 11 { 12 if (context.Request.Browser.Browser == "InternetExplorer") 13 fileName = HttpUtility.UrlEncode(fileName);//编码 14 context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName); 15 context.Response.BinaryWrite(ms.ToArray()); //进行二进制流下载 16 } 17 //生成excel内存流 18 public static MemoryStream RenderToExcel<T>(string title,IEnumerable<T> data)where T : class 19 { 20 if (typeof(T).GetCustomAttribute(typeof(DataContractAttribute)) == null) 21 { 22 var properties = typeof(T).GetProperties(); //获取所有公共属性 23 Dictionary<PropertyInfo, string> columnNames = new Dictionary<PropertyInfo, string>(); 24 foreach (var p in properties) 25 { 26 var attr = p.GetCustomAttribute(typeof(DataMemberAttribute)) as DataMemberAttribute; //获取属性的绑定特性名 27 if (attr == null) 28 { 29 columnNames.Add(p, p.Name); 30 } 31 else 32 { 33 columnNames.Add(p, attr.Name); 34 } 35 } 36 IWorkbook workbook = GetIWorkbook(null, ".xls"); //创建一个工作薄 37 ISheet sheet=workbook.CreateSheet();//创建一个工作页 38 #region 标题及字段赋值 39 if(!string.IsNullOrWhiteSpace(title)) 40 { 41 IRow firstrow=sheet.CreateRow(0); 42 firstrow.CreateCell(columnNames.Count / 2).SetCellValue(title); 43 } 44 IRow headerRow = sheet.CreateRow(1);int columnId = 0; 45 foreach (var p in columnNames.Keys) 46 { 47 headerRow.CreateCell(columnId++).SetCellValue(columnNames[p]); 48 } 49 #endregion 50 #region 数据赋值 51 int rowIndex = 2;foreach (var item in data) 52 { 53 columnId = 0; 54 IRow dataRow = sheet.CreateRow(rowIndex++); 55 foreach (var p in columnNames.Keys) 56 { 57 dataRow.CreateCell(columnId++).SetCellValue(p.GetValue(item) == null? string.Empty: p.GetValue(item).ToString()); 58 } 59 } 60 #endregion 61 AutoSizeColumns(sheet); 62 MemoryStream ms = new MemoryStream(); 63 workbook.Write(ms); //写入内存流 64 ms.Flush(); 65 ms.Position = 0; 66 workbook = null; 67 sheet = null; 68 return ms; 69 } 70 71 //创建对应格式的工作薄 72 private static IWorkbook GetIWorkbook(Stream excelFileStream, string ext) 73 { 74 if (ext == ".xlsx") 75 return excelFileStream == null ? new XSSFWorkbook() : new XSSFWorkbook(excelFileStream); 76 return excelFileStream == null ? new HSSFWorkbook() : new HSSFWorkbook(excelFileStream); 77 } 78 } 79 //设置列自适应 80 private static void AutoSizeColumns(ISheet sheet) 81 { 82 if (sheet.PhysicalNumberOfRows > 0) 83 { 84 IRow headerRow = sheet.GetRow(0); 85 for (int i = 0, l = headerRow.LastCellNum; i < l; i++) 86 { 87 sheet.AutoSizeColumn(i); 88 } 89 } 90 }