【问题标题】:Apache POI insert image without anchorApache POI插入没有锚点的图像
【发布时间】:2017-04-13 20:27:21
【问题描述】:

我正在使用 Apache POI 在 Java 中创建 Excel 文件,它可以工作,但插入的图像被锚定到列/行。这种方法有两个问题:

  1. 图像未保持原始大小(稍微拉伸)。

  2. 调整列/行大小时,图像会被拉伸。有没有办法在没有锚的情况下将图像插入到 Excel 中? (与使用 Excel / 插入 / 图片相同)

我正在使用 Apache POI 文档页面中的以下示例:

//create a new workbook
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();

//add picture data to this workbook.
InputStream is = new FileInputStream("image1.jpeg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();

CreationHelper helper = wb.getCreationHelper();

//create sheet
Sheet sheet = wb.createSheet();

// Create the drawing patriarch.  This is the top level container for all shapes. 
Drawing drawing = sheet.createDrawingPatriarch();

//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it
anchor.setCol1(3);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);

//auto-size picture relative to its top-left corner
pict.resize();

//save workbook
String file = "picture.xls";
if(wb instanceof XSSFWorkbook) file += "x";
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();

感谢您的回答。

【问题讨论】:

  • 我找到了解决方案 2:anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
  • 你解决了 #1 的问题了吗?

标签: apache-poi insert-image


【解决方案1】:

可能是因为方法 'resize' javadoc 中的这个注释:

请注意,此方法仅适用于具有默认字体大小的工作簿(Arial 10pt 用于 .xls,Calibri 11pt 用于 .xlsx)。如果更改默认字体,则调整大小的图像可以垂直或水平拉伸。

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多