0

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

  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();

感谢您的回答。

4

1 回答 1

1

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

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

于 2017-04-13T12:27:21.187 回答