Search code examples
javaexcelspring-bootapache-poixssf

Apache POI: Multiple cell comments in one cell are not allowed


I'm trying to add comment to cells. The code works fine for 2 rows. But when the row number goes to third, it starts giving me the error:-

java.lang.IllegalArgumentException: Multiple cell comments in one cell are not allowed

I add the comment when I detect an exception while reading from cell value. Given is the method which I use for adding the comment:-

private void cellException(Sheet datatypeSheet, CellStyle cellErrorStyle, Row invCurrentRow,
        int invCellNum, String mainMessage)
{

    Cell mainCell = invCurrentRow.getCell(invCellNum);

    if (ExcelUtility.checkIfCellValueAbsent(mainCell))
        mainCell = invCurrentRow.createCell(invCellNum);

    mainCell.setCellStyle(cellErrorStyle);

    Comment mainComment = mainCell.getCellComment();

    if (Util.isNullOrEmpty(mainComment))
        mainComment = datatypeSheet.createDrawingPatriarch().createCellComment(
                new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
    mainComment.setString(new XSSFRichTextString(mainMessage));
    mainCell.setCellComment(mainComment);
    datatypeSheet.autoSizeColumn(mainCell.getColumnIndex());
}

This code works perfect for two rows. I don't understand what goes wrong with the third row.

I'm using XSSFWorkbook and following is the dependency I added in my springboot project:-

<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.17</version>
    </dependency>

I tried searching for answer and I found one which I thought could be useful but it wasn't:-

Multiple comments apache poi


Solution

  • You are creating all cell comments using the same anchor which starts on column index 3, row index 3, which is D4. So all your cell comments belongs to D4. Then, if you try creating a cell comment using that same anchor and there is already a comment in D4, this leads to the error:

    java.lang.IllegalArgumentException: Multiple cell comments in one cell are not allowed, cell: D4
    

    Do using different achors for each cell comment:

    ...
      if (mainComment == null)
       mainComment = datatypeSheet.createDrawingPatriarch().createCellComment(
                      //new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
                      new XSSFClientAnchor(0, 0, 0, 0, mainCell.getColumnIndex(), mainCell.getRowIndex(), mainCell.getColumnIndex()+2, mainCell.getRowIndex()+3));
    ...