在apache poi中使用HSSFClientAnchor创建单元格注释

时间:2010-02-17 14:00:16

标签: java apache-poi

有人可以在创建单元格注释时向我解释如何正确使用Anchors吗?我的工作正在进行,但电子表格发生了变化,我在查看单元格注释时出现问题。这是我使用的代码:

 Comment c = drawing.createCellComment (new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short)6, 5));

这主要是通过试验来找到的。看看它的api并没有让它更清楚。

根据快速入门指南,我也试过以下但没有运气:

ClientAnchor anchor = chf.createClientAnchor();
Comment c = drawing.createCellComment(anchor);
c.setString(chf.createRichTextString(message)); 

2 个答案:

答案 0 :(得分:5)

有点晚了,但这可能会奏效(它对我有用,而快速启动的Apache POI示例对我来说也不起作用):

    public void setComment(String text, Cell cell) {
    final Map<Sheet, HSSFPatriarch> drawingPatriarches = new HashMap<Sheet, HSSFPatriarch>();

    CreationHelper createHelper = cell.getSheet().getWorkbook().getCreationHelper();
    HSSFSheet sheet = (HSSFSheet) cell.getSheet();
    HSSFPatriarch drawingPatriarch = drawingPatriarches.get(sheet);
    if (drawingPatriarch == null) {
        drawingPatriarch = sheet.createDrawingPatriarch();
        drawingPatriarches.put(sheet, drawingPatriarch);
    }

    Comment comment = drawingPatriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
    comment.setString(createHelper.createRichTextString(text));
    cell.setCellComment(comment);
}

Erik Pragt

答案 1 :(得分:4)

以下代码适用于Office 2007(xlsx)格式文件。从POI指南中找出这一点 http://poi.apache.org/spreadsheet/quick-guide.html#CellCommentsHow to set comments for 3 cells using apache poi

protected void setCellComment(Cell cell, String message) {
    Drawing drawing = cell.getSheet().createDrawingPatriarch();
    CreationHelper factory = cell.getSheet().getWorkbook()
            .getCreationHelper();
    // When the comment box is visible, have it show in a 1x3 space
    ClientAnchor anchor = factory.createClientAnchor();
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex() + 1);
    anchor.setRow1(cell.getRowIndex());
    anchor.setRow2(cell.getRowIndex() + 1);
    anchor.setDx1(100);
    anchor.setDx2(100);
    anchor.setDy1(100);
    anchor.setDy2(100);

    // Create the comment and set the text+author
    Comment comment = drawing.createCellComment(anchor);
    RichTextString str = factory.createRichTextString(message);
    comment.setString(str);
    comment.setAuthor("Apache POI");
    // Assign the comment to the cell
    cell.setCellComment(comment);
}