使用Apache POI自动调整Excel注释大小

6

我们有很多由Apache POI生成的Excel报告。其中一些报告包含标题中的注释。由于有很多报告,我们想要创建通用解决方案来添加注释。正如我们所注意到的那样,可以通过以下代码将注释添加到单元格中:

public static void addComment(final Workbook workbook, final Sheet sheet, final Cell cell, final Row row,
        final String comment) {

    final CreationHelper factory = workbook.getCreationHelper();

    final Drawing drawing = sheet.createDrawingPatriarch();

    final ClientAnchor anchor = factory.createClientAnchor();
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex() + 3);
    anchor.setRow1(row.getRowNum());
    anchor.setRow2(row.getRowNum() + 5);

    final Comment cellComment = drawing.createCellComment(anchor);
    final RichTextString richText = factory.createRichTextString(comment);
    cellComment.setString(richText);
    cell.setCellComment(cellComment);
}

我们还注意到,评论框的大小可以使用列/行索引来设置 - 这对我们来说是主要问题,因为如果第一列有100像素,而第二列有1000像素,那么评论框的宽度将为1000像素。这里是我们的问题 - 是否有可能使用像素而不是列/行索引来设置评论框大小,使用apache poi?或者也许有一些方法可以使用apache poi自动计算评论框的大小?

请查看此答案 https://stackoverflow.com/questions/11780348/changing-size-of-cell-comments-in-apache-poi/17722067#17722067 - SydMK
2个回答

0

ClientAnchor支持偏移量,至少特定的实现支持:

public XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2)

dx1是距左侧的偏移量,dx2是距右侧的偏移量,dy1是距顶部的偏移量,dy2是距底部的偏移量(col1,row1是起始行列,col2,row2是结束行列,不包括在内)。

因此,要减小宽度,只需将非零值分配给dx2即可。

dx1,dx2,dy1和dy2以英语度量单位(EMU)为单位。每个EMU有9525个像素,因此您必须使用相当大的值。


0

在这里添加一个答案,以自动调整评论框的大小,以防其他人仍在搜索!添加评论后,只需使用以下代码:

import org.apache.poi.ss.usermodel.*;
import com.microsoft.schemas.vml.*;
...
XSSFVMLDrawing vmlDrawing = ((OoxmlSheetExtensions)sheet).getVMLDrawing(false);
CTShape commentShape = vmlDrawing.findCommentShape(row, column);    
CTTextBox textBox = commentShape.getTextboxArray()[0];
textBox.setStyle(textBox.getStyle() + ";mso-fit-shape-to-text:t");

我是通过查看“格式批注...”窗口中“对齐”选项卡中的“自动大小”复选框单击时生成的XML找到这个的。更多信息请参见此处

无论这在后续版本的Excel中是否会改变,因为VML已被弃用,所以目前还不确定。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接