首先我用的是xlsx,查了一下,首先创建多个合并的单元格 ,然后用RegionUtil设置CellRangeAddress对象的边框。
直接上代码
/**
* 合并单元格并填充内容
*
* @param sheet
* @param rowIdx 行数
* @param colIdx 列数
* @param text 单元格填充的文本
* @param workbook workbook
* @param crossColumn 要跨的列数
*/
private static void writeTextToCellBackInfoCross(Sheet sheet, int rowIdx, int colIdx, String text,Workbook workbook,int crossColumn) {
Row row = sheet.getRow(rowIdx);
if (row == null) {
row = sheet.createRow(rowIdx);
}
// Cell cell = row.getCell(colIdx);
// if (cell == null) {
// cell = row.createCell(colIdx);
// }
//
// cell.setCellValue(text);
// CellStyle style = workbook.createCellStyle();
// style.setBorderTop(BorderStyle.THIN);
// style.setBorderBottom(BorderStyle.THIN);
// style.setBorderLeft(BorderStyle.THIN);
// style.setBorderRight(BorderStyle.HAIR);
// 合并单元格
CellRangeAddress mergedRegion = new CellRangeAddress(
rowIdx, // 起始行索引
rowIdx, // 结束行索引
colIdx, // 起始列索引
colIdx+crossColumn // 结束列索引
);
sheet.addMergedRegion(mergedRegion);
// 合并单元格后,
for(int i =colIdx ; i< colIdx + crossColumn ;i++){
Cell cell = row.getCell(i);
if (cell == null) {
cell = row.createCell(i);
}
cell.setCellValue(text);
// cell.setCellStyle(style);
}
// poi存在问题,常规设置合并后的单元格边框会缺失边框,需要使用RegionUtil设置合并后的单元格
setRegionBorder(mergedRegion,sheet,workbook);
}
/**
* @param border 边框宽度
* @param region 合并单元格区域范围
* @param sheet
* @param wb
*/
public static void setRegionBorder(CellRangeAddress region, Sheet sheet,Workbook wb){
BorderStyle bordertemp = BorderStyle.THIN;
RegionUtil.setBorderTop(bordertemp, region, sheet);
RegionUtil.setBorderRight(bordertemp, region, sheet);
RegionUtil.setBorderBottom(bordertemp, region, sheet);
RegionUtil.setBorderLeft(bordertemp, region, sheet);
}