1.操作Excel
准备生成的公共方法(将数据源DataTable转换成MemoryStream)
1 /// <summary> 2 /// 生成Excel 3 /// </summary> 4 /// <param name="table">DataTable</param> 5 /// <returns>MemoryStream</returns> 6 public static MemoryStream BuildToExcel(DataTable table) 7 { 8 MemoryStream ms = new MemoryStream(); 9 10 using (table) 11 { 12 using (IWorkbook workbook = new HSSFWorkbook()) 13 { 14 using (ISheet sheet = workbook.CreateSheet()) 15 { 16 IRow headerRow = sheet.CreateRow(0); 17 18 // handling header. 19 foreach (DataColumn column in table.Columns) 20 { 21 headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption); 22 } 23 24 // handling value. 25 int rowIndex = 1; 26 27 foreach (DataRow row in table.Rows) 28 { 29 IRow dataRow = sheet.CreateRow(rowIndex); 30 31 foreach (DataColumn column in table.Columns) 32 { 33 dataRow.CreateCell(column.Ordinal, CellType.STRING).SetCellValue(row[column].ToString()); 34 } 35 36 rowIndex++; 37 } 38 39 AutoSizeColumns(sheet); 40 workbook.Write(ms); 41 ms.Flush(); 42 ms.Position = 0; 43 } 44 } 45 } 46 47 return ms; 48 }