Apache POI移除Excel单元格批注失效问题排查与解决
解决POI无法移除Excel批注的问题
问题原因
你当前代码使用row.cellIterator()遍历单元格,这个迭代器只会返回已创建的单元格(即有内容、样式或被编辑过的单元格)。但批注常常会添加在空白单元格上,这些空白单元格不会被cellIterator()遍历到,导致cell.removeCellComment()根本没执行到这些带批注的空白单元格,所以批注没被完全移除。
修复方案
改为遍历行内的所有列索引,包括空白单元格,确保每个单元格都被处理:
private List<AssetContent> removeBgColorAndComments(final List<AssetContent> contents) throws IOException { for (AssetContent content : contents) { try (final FileInputStream inputStream = new FileInputStream(content.getTemporaryFile()); final XSSFWorkbook workbook = new XSSFWorkbook(inputStream); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { final CellStyle style = workbook.createCellStyle(); style.setFillBackgroundColor(IndexedColors.WHITE.getIndex()); for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); ++sheetIndex) { XSSFSheet sheet = workbook.getSheetAt(sheetIndex); // 遍历所有行 for (int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); if (row == null) { continue; } // 获取该行的最大列数,遍历所有列 int lastCellNum = row.getLastCellNum(); for (int colNum = 0; colNum < lastCellNum; colNum++) { // 即使单元格不存在,也创建空白单元格处理 Cell cell = row.getCell(colNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); cell.setCellStyle(style); cell.removeCellComment(); } } } workbook.write(byteStream); content.setTemporaryFile(AssetContentUtils.createAssetContentTempFile(new ByteArrayInputStream(byteStream.toByteArray()))); content.setContentLength(byteStream.size()); } } return contents; }
额外说明
- 使用
Row.MissingCellPolicy.CREATE_NULL_AS_BLANK可以确保即使单元格原本不存在(空白),也会创建一个空白单元格对象,这样就能处理其中的批注。 - 遍历行时要判断
row == null,避免空指针(因为Excel里可能存在空行,即没有任何单元格的行)。
内容的提问来源于stack exchange,提问作者Sajith dilshan
相关产品推荐
相关产品推荐

