今天用POI导出Excel的时候,发现导出的单元格确少边框,最后发现有2个方案可以解决。
方案一
CellRangeAddress的4个参数分别表示:起始行号,终止行号, 起始列号,终止列号
// 使用这种方式合并单元格时,要给单元格逐一设置带边框的样式sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 3));// 例如:HSSFCellStyle defaultStyle = ExportToExcelUtil.setDefaultStyle(workbook);// 为单元格设置带边框的样式setCellStyles(row, 2, 3, defaultStyle );/*** 设置单元格样式*/private void setCellStyles(HSSFRow row, int start, int end, HSSFCellStyle cellStyle) {for (int i = start; i <= end; i++) {cell = row.createCell(i);cell.setCellStyle(cellStyle);}} /*** 带边框的样式+*/public static HSSFCellStyle setDefaultStyle(HSSFWorkbook workbook) {HSSFCellStyle cellStyle = workbook.createCellStyle();// 边框cellStyle.setBorderBottom(BorderStyle.THIN);cellStyle.setBorderLeft(BorderStyle.THIN);cellStyle.setBorderRight(BorderStyle.THIN);cellStyle.setBorderTop(BorderStyle.THIN);return cellStyle;}
方案二
// 合并单元格CellRangeAddress region = new CellRangeAddress(1, 1, 2, 2);sheet.addMergedRegion(region);// 合并之后为合并的单元格设置样式setRegionStyle(sheet, region, defaultStyle);/*** 为合并的单元格设置样式(可根据需要自行调整)*/@SuppressWarnings("deprecation")public static void setRegionStyle(HSSFSheet sheet, CellRangeAddress region, HSSFCellStyle cs) {for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {HSSFRow row = sheet.getRow(i);if (null == row) row = sheet.createRow(i);for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {HSSFCell cell = row.getCell(j);if (null == cell) cell = row.createCell(j);cell.setCellStyle(cs);}}}