NPOI导出Excel表格的操作(.Net2.0)
常用操作如下:
private void ExportExcel() { HSSFWorkbook workbook = new HSSFWorkbook(); FileStream fs = new FileStream("d:/a.xls", FileMode.OpenOrCreate); ISheet sheet = workbook.CreateSheet("sheet1"); //表头,单元格合并 IRow rowTitle = sheet.CreateRow(0); rowTitle.Height = 30 * 20; ICell cellTitle = rowTitle.CreateCell(0); ICellStyle titleCellStyle = workbook.CreateCellStyle(); titleCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;//水平居中 titleCellStyle.VerticalAlignment =VerticalAlignment.CENTER;//垂直居中 IFont titleFont = workbook.CreateFont(); titleFont.FontHeight = 20 * 20; titleFont.Color = HSSFColor.GREEN.index; titleFont.Boldweight = 23; cellTitle.SetCellValue("NPOI综合测试范例"); cellTitle.CellStyle = titleCellStyle; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 5));//合并单元格 IRow headerRow = sheet.CreateRow(1); ICell cell1 = headerRow.CreateCell(0); cell1.SetCellType(CellType.STRING); cell1.SetCellValue("张三"); //插入大数字,用文本形式显示 ICell cell2 = headerRow.CreateCell(1); cell2.SetCellValue("23123456789012345"); //插入时间 ICell cell3 = headerRow.CreateCell(2); ICellStyle style = workbook.CreateCellStyle(); IDataFormat format = workbook.CreateDataFormat(); style.DataFormat = format.GetFormat("yyyy-mm-dd"); sheet.SetColumnWidth(2, 30 * 256);//设置列宽,也就是设置整个表格的列宽。 cell3.CellStyle = style; //设置颜色 style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.RED.index; style.FillPattern = FillPatternType.SOLID_FOREGROUND; DateTime dt = DateTime.Now; cell3.SetCellValue(dt); ICell cell4 = headerRow.CreateCell(3); cell4.SetCellType(CellType.NUMERIC); cell4.SetCellValue(92); ICell cell5 = headerRow.CreateCell(4); cell5.SetCellType(CellType.NUMERIC); cell5.SetCellValue(78); //插入公式 ICell cell6 = headerRow.CreateCell(5); cell6.SetCellFormula("sum(D2:E2)"); //插入超链接 IRow row2 = sheet.CreateRow(2); row2.Height = 30 * 20;//设置行高 ICell cel7 = row2.CreateCell(0); ICellStyle linkStyle = workbook.CreateCellStyle(); IFont linkFont = workbook.CreateFont(); linkFont.Color = HSSFColor.BLUE.index; linkFont.Underline = (byte)FontUnderlineType.SINGLE; linkStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;//设置居中 linkStyle.SetFont(linkFont); cel7.SetCellValue("URL Link"); HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.URL); link.Address = ("http://poi.apache.org/"); cel7.Hyperlink = (link); cel7.CellStyle = (linkStyle); workbook.Write(fs); fs.Close(); }

浙公网安备 33010602011771号