1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| public void WriteToExcel(string filePath) { IWorkbook wb; string extension = System.IO.Path.GetExtension(filePath); if (extension.Equals(".xls")) { wb = new HSSFWorkbook(); } else { wb = new XSSFWorkbook(); }
ICellStyle style1 = wb.CreateCellStyle(); style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; style1.WrapText = true;
ICellStyle style2 = wb.CreateCellStyle(); IFont font1 = wb.CreateFont(); font1.FontName = "楷体"; font1.Color = HSSFColor.Red.Index; font1.Boldweight = (short)FontBoldWeight.Normal; style2.SetFont(font1); style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; style2.FillPattern = FillPattern.SolidForeground; style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
ICellStyle dateStyle = wb.CreateCellStyle(); dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; IDataFormat dataFormatCustom = wb.CreateDataFormat(); dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
ISheet sheet = wb.CreateSheet("Sheet0"); int[] columnWidth = { 10, 10, 20, 10 }; for (int i = 0; i < columnWidth.Length; i++) { sheet.SetColumnWidth(i, 256 * columnWidth[i]); }
int rowCount = 3, columnCount = 4; object[,] data = { {"列0", "列1", "列2", "列3"}, {"", 400, 5.2, 6.01}, {"", true, "2014-07-02", DateTime.Now} };
IRow row; ICell cell; for (int i = 0; i < rowCount; i++) { row = sheet.CreateRow(i); for (int j = 0; j < columnCount; j++) { cell = row.CreateCell(j); cell.CellStyle = j % 2 == 0 ? style1 : style2; object obj = data[i, j]; SetCellValue(cell, data[i, j]); if (obj.GetType() == typeof(DateTime)) { cell.CellStyle = dateStyle; } } }
CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0); sheet.AddMergedRegion(region);
try { FileStream fs = File.OpenWrite(filePath); wb.Write(fs); fs.Close(); } catch (Exception e) { Debug.WriteLine(e.Message); } }
|