views:

227

answers:

1

I need to add a comment to an HSSF Cell in Excel. Everything works fine the very first time but if I open the same file and run the code again it corrupts the file.

I've also noticed that I need to create a Drawing object on a Sheet only once:

_sheet.createDrawingPatriarch();

If the line above gets executed more than once comments will not work.

So has anyone tried adding comments to Cells, closing the file, opening the file again and trying to add more comments to different cells?

The below code works but if I open the file again then comments are not added, plus the file gets corrupted!!!

Is there a way to get the existing Drawing object from a Sheet?

Any ideas appreciated. Thanks!!

_drawing = (HSSFPatriarch) _sheet.createDrawingPatriarch();

Row row = _sheet.getRow(rowIndex_);
Cell cell = row.getCell(0);
CreationHelper factory = _workbook.getCreationHelper();

HSSFAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short)6, 5);
        org.apache.poi.ss.usermodel.Comment comment = _drawing.createComment(anchor);
RichTextString str = factory.createRichTextString("Hello, World "+rowIndex_);
comment.setString(str);

  cell.setCellComment(comment);
A: 

Disclaimer: I've got no particular experience with this.

However, I do note that the the Javadoc for createDrawingPatriarch() notes that it will destroy any previous graphics (including, I guess comments, since it appears that comments are stored as part of the drawing patriarch). Have you tried first checking to see whether the document has a drawing patriarch and only creating it if it doesn't, e.g.,

HSSFPatriarch drawing = document.getDrawingPatriarch()
if (drawing == null)
    drawing = document.createDrawingPatriarch()

It still seems that this may be somewhat fragile given the comments in the documentation for getDrawingPatriarch(), but I suspect it may work for your use-case.

ig0774
Well it does exactly what the WARNING says. The stored image get corrupted when saving file the second time. Only the newly images get created. Thanks for the response.
Marquinio