使用POI在Excel中拉伸图像

在我的应用程序中,我使用POI API生成一个Excel文件。 文档左上angular的一个单元格包含图像。 我得到的问题是图像被拉伸,以填补它的细胞。

根据我在Picture对象上使用哪种resize的方法,图像会以各种大小显示,但它总是具有其所在的单元格的水平 – 垂直比率,换句话说,它不会保持自己的比例。

这是我的代码:

titleRow = sheet.createRow(0); titleRow.setHeightInPoints(25f); titleRow.createCell(0); sheet.getRow(0).getCell(0).setCellStyle(defaultTitleStyle(wb)); WebApplicationContext webCtx = ((WebApplicationContext)AtlasApplicationUtils.getCurrentApplication().getContext()); ServletContext sc = webCtx.getHttpSession().getServletContext(); String contextPath = sc.getContextPath(); // sc.getResourceAsStream(contextPath + "/VAADIN/themes/m2m/../m2m/img/gnd_logo_white.png") String f = new File("").getAbsolutePath(); InputStream is = new FileInputStream(System.getProperty("user.dir") + "/src/main/webapp/VAADIN/themes/m2m/img/gnd_logo_white.png"); byte[] bytes = IOUtils.toByteArray(is); int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); is.close(); CreationHelper helper = wb.getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(0); anchor.setRow1(0); sheet.autoSizeColumn(0); Picture pict = drawing.createPicture(anchor, pictureIdx); pict.getPreferredSize(); pict.resize(0.25); 

造型方法:

 protected CellStyle defaultTitleStyle(final HSSFWorkbook wb) { CellStyle style; final Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 18); titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); titleFont.setColor(IndexedColors.GREY_80_PERCENT.getIndex()); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); // style.setFillBackgroundColor(IndexedColors.BLUE_GREY.getIndex()); style.setFont(titleFont); HSSFPalette palette = wb.getCustomPalette(); palette.setColorAtIndex(HSSFColor.BLUE_GREY.index, (byte) 7, (byte) 64, (byte) 127); palette.setColorAtIndex(HSSFColor.GREY_80_PERCENT.index, (byte) 228, (byte) 228, (byte) 228); return style; 

有没有人知道一种方法来避免这个问题,让图像保持原来的比例?

文档中有一些警告。

void resize()

将图像重置为原始大小。

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