我正在使用Apache POI在Java中创建Excel文件,它可以工作,但插入的图像锚定到列/行。这种方法存在两个问题:
图像不保持原始尺寸(拉伸一点点)。
调整列/行的大小时,图像会被拉伸。有没有办法在没有锚点的情况下将图像插入Excel? (与使用Excel / Insert / Picture相同)
我在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();
感谢您的回答。
答案 0 :(得分:1)
正是因为这个评论方法'调整大小' javadoc:
请注意,此方法仅适用于具有默认字体大小的工作簿(.xls为Arial 10pt,.xlsx为Calibri 11pt)。如果更改了默认字体,则可以垂直或水平拉伸已调整大小的图像。