Apache POI Java合并Excel单元格后内容无法居中的问题排查
解决Apache POI合并单元格内容不居中问题
你的代码核心问题出在内容单元格的位置和合并区域不匹配:你把品牌内容放在了sheet.getLastRowNum() + 1这一行,但合并的是rowStartNum到rowEndNum的区域,这导致内容根本不在合并范围内,自然无法居中显示在合并单元格里。
另外,你已经在brandStyle里设置了居中对齐,后面用CellUtil重复设置属于冗余操作,还可能因为样式覆盖出问题。
修正后的代码如下:
public void mergeColumn(final String brand, final int rowStartNum, final int rowEndNum, final String category) { final XSSFSheet sheet = wb.getSheet(category); // 合并区域的内容必须放在起始行(rowStartNum)的对应列,Excel只认合并区域左上角单元格的内容 XSSFRow targetRow = sheet.getRow(rowStartNum); targetRow = targetRow == null ? sheet.createRow(rowStartNum) : targetRow; final int targetColumn = 1; // 第二列,索引从0开始 XSSFCell currentBrandCell = targetRow.getCell(targetColumn); currentBrandCell = currentBrandCell == null ? targetRow.createCell(targetColumn) : currentBrandCell; currentBrandCell.setCellValue(brand); currentBrandCell.setCellStyle(cellStyle.getBrandStyle()); // 创建合并区域:行从rowStartNum到rowEndNum,列固定为第二列(索引1) sheet.addMergedRegion(new CellRangeAddress( rowStartNum, rowEndNum, targetColumn, targetColumn )); sheet.autoSizeColumn(targetColumn, true); // 移除多余的createRow,避免创建不必要的空行 // sheet.createRow(rowEndNum + 1); }
同时检查你的brandStyle定义,注意POI新版本中CellStyle.ALIGN_CENTER已被弃用,建议改用新常量避免版本兼容问题:
brandStyle = wb.createCellStyle(); brandStyle.setFont(topHeadearFont2); // 替换弃用的对齐常量 brandStyle.setAlignment(HorizontalAlignment.CENTER); brandStyle.setVerticalAlignment(VerticalAlignment.CENTER); putBordersThick(brandStyle);
关键注意事项
- Excel合并单元格的内容仅会显示合并区域左上角单元格的内容,所以必须把内容放在
rowStartNum行、目标列的单元格中 - 尽量复用全局样式对象,不要每次创建新样式,否则会超出Excel的样式数量限制
内容的提问来源于stack exchange,提问作者Kahn Sparkle
相关产品推荐
相关产品推荐

