1 /// <summary> 2 /// 导出Excel 3 /// 纵排顺序是按实体类定义属性前后顺序 4 /// </summary> 5 /// <param name="lists">数据集合</param> 6 /// <param name="sheetHead">中文列名对照("属性名","表头名");默认属性名</param> 7 /// <param name="workbookFile">保存路径</param> 8 public static byte[] ExportToExcel<T>(IList<T> lists, Hashtable sheetHead, string workbookFile) 9 { 10 var workbook = new HSSFWorkbook(); 11 var ms = new MemoryStream(); 12 var sheet = workbook.CreateSheet() as HSSFSheet; 13 var headerRow = sheet.CreateRow(0) as HSSFRow; 14 var isHeadRow = true; 15 var rawStart = 1; 16 var type = typeof(T); 17 var properties = type.GetProperties(); 18 19 foreach (var item in lists) 20 { 21 var dataRow = sheet.CreateRow(rawStart) as HSSFRow; 22 var cellNum = 0; 23 foreach (var column in properties) 24 { 25 if (isHeadRow) 26 { 27 // 若不存在,默认属性名 28 if (headerRow != null) 29 headerRow.CreateCell(cellNum).SetCellValue(sheetHead[column.Name] == null ? column.Name : sheetHead[column.Name].ToString()); 30 if (dataRow != null) 31 dataRow.CreateCell(cellNum).SetCellValue(column.GetValue(item, null) == null ? "" : column.GetValue(item, null).ToString()); 32 } 33 else 34 { 35 if (dataRow != null) 36 dataRow.CreateCell(cellNum).SetCellValue(column.GetValue(item, null) == null ? "" : column.GetValue(item, null).ToString()); 37 } 38 39 //列宽自适应,只对英文和数字有效 40 sheet.AutoSizeColumn(cellNum); 41 cellNum++; 42 } 43 isHeadRow = false; 44 rawStart++; 45 } 46 47 workbook.Write(ms); 48 ms.Flush(); 49 ms.Position = 0; 50 sheet = null; 51 headerRow = null; 52 workbook = null; 53 var data = ms.ToArray(); 54 55 if (!string.IsNullOrEmpty(workbookFile)) 56 { 57 var dic = Path.GetDirectoryName(workbookFile); 58 59 // 创建目录 60 if (dic != null && !Directory.Exists(dic)) 61 { 62 Directory.CreateDirectory(dic); 63 } 64 65 FileStream fs = new FileStream(workbookFile, FileMode.Create, FileAccess.Write); 66 fs.Write(data, 0, data.Length); 67 fs.Flush(); 68 fs.Close(); 69 fs = null; 70 } 71 72 ms = null; 73 74 return data; 75 }
时间复杂度(n*n),不知道你里面的循环是什么需求,但是,注意数据量大了是会慢,你可以异步去处理,给用户一个自己下载的页面,不要把整个页面卡住
现在知道主要是读取数据库数据过慢导致
试试引入多线程
现在知道主要是读取数据库数据过慢导致
数据多了是慢,现在npoi我基本只用来做导入了,导出用报表做,快很多。
现在知道主要是读取数据库数据过慢导致