NPOI的C# Helper代碼2
1 public static MemoryStream ExportXls(DataTable dt) 2 { 3 HSSFWorkbook wk = new HSSFWorkbook(); 4 ISheet sheet = null; 5 6 string sheetName = "Sheet1"; 7 if (!string.IsNullOrEmpty(dt.TableName)) 8 { 9 sheetName = dt.TableName; 10 } 11 sheet = wk.CreateSheet(sheetName); 12 //列頭及樣式 13 IRow headerRow = sheet.CreateRow(0); 14 ICellStyle headStyle = wk.CreateCellStyle(); 15 headStyle.Alignment = HorizontalAlignment.Center; 16 17 IFont font = wk.CreateFont(); 18 font.FontHeightInPoints = 10; 19 font.Boldweight = 700; 20 font.FontName = "微雅黑體"; 21 headStyle.SetFont(font); 22 23 foreach (DataColumn column in dt.Columns) //column共屬性 24 { 25 headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption); //clomun.ColumnName 26 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //體會 27 } 28 29 int rowIndex = 1; 30 foreach (DataRow row in dt.Rows) 31 { 32 //HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); //也可以這樣寫 33 IRow dataRow = sheet.CreateRow(rowIndex); 34 foreach (DataColumn column in dt.Columns) 35 { 36 dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); 37 } 38 rowIndex++; 39 } 40 MemoryStream ms = new MemoryStream(); 41 wk.Write(ms); 42 ms.Flush(); 43 return ms; 44 } 45 46 //輸出 47 public static void SaveToFile(MemoryStream ms) 48 { 49 using (FileStream fs = File.OpenWrite(@"c:\1.xls")) 50 { 51 byte[] data = ms.ToArray(); 52 fs.Write(data,0,data.Length); 53 fs.Flush(); 54 data = null; 55 } 56 } 57 public static void SaveToFile(MemoryStream ms, string filePath) 58 { 59 using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) 60 { 61 byte[] data = ms.ToArray(); 62 fs.Write(data,0,data.Length); 63 fs.Flush(); 64 data = null; 65 } 66 }View Code