我需要使用POI为xls-document添加形状(特别是圆形)。所以,我写了以下代码:
private void drawLabel(HSSFSheet sheet, HSSFCell cell) {
final short columnIndex = (short) cell.getColumnIndex();
final int rowIndex = cell.getRowIndex();
HSSFClientAnchor anchor = new HSSFClientAnchor(60, 60, 200, 200, columnIndex, rowIndex, columnIndex, rowIndex);
anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);
HSSFSimpleShape shape = sheet.getDrawingPatriarch().createSimpleShape(anchor);
shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
...
}
有效。但是,如果我尝试以编程方式更改列宽(例如sheet.setColumnWidth(0, 5 * 256);
(假设已将形状添加到具有列索引== 0的单元格)),则圆扭曲并变为椭圆形(尽管锚的类型设置为{{ 1}})。
我的方法有什么问题,是否有办法绘制一个不会与相应的单元格一起调整大小的形状?
答案 0 :(得分:0)
我找不到这个问题的正确解决方法。但解决问题的一种方法是根据实际尺寸缩放形状(特别是其锚点):
private void drawLabel(HSSFSheet sheet, HSSFCell cell) {
final int defaultColumnWidth = 2048; // column width before resizing
final int defaultRowHeight = 255; // row height before resizing
final double xDistortionFactor = 1.0 * defaultColumnWidth / sheet.getColumnWidth(cell.getColumnIndex());
final double yDistortionFactor = 1.0 * defaultRowHeight / cell.getRow().getHeight();
final int dx1 = (int) (60 * xDistortionFactor);
final int dy1 = (int) (60 * yDistortionFactor);
final int dx2 = (int) (200 * xDistortionFactor);
final int dy2 = (int) (200 * yDistortionFactor);
final short columnIndex = (short) cell.getColumnIndex();
final int rowIndex = cell.getRowIndex();
final HSSFClientAnchor anchor = new HSSFClientAnchor(dx1, dy1, dx2, dy2, columnIndex, rowIndex, columnIndex, rowIndex);
anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);
HSSFSimpleShape shape = sheet.getDrawingPatriarch().createSimpleShape(anchor);
shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
...
}
这个解决方案并不优雅,但它确实有效。