Java 使用POI在Excel中拉伸图像
在我的应用程序中,我使用POI API生成一个Excel文件。文档左上角的一个单元格包含图像。我遇到的问题是图像被拉伸以填充容纳它的单元格 根据我在图片对象上使用的调整大小的方法,图像以不同的大小显示,但它始终具有它所在的单元格所具有的水平-垂直比率,换句话说,它不会保持自己的比率 这是我的代码:Java 使用POI在Excel中拉伸图像,java,excel,apache-poi,Java,Excel,Apache Poi,在我的应用程序中,我使用POI API生成一个Excel文件。文档左上角的一个单元格包含图像。我遇到的问题是图像被拉伸以填充容纳它的单元格 根据我在图片对象上使用的调整大小的方法,图像以不同的大小显示,但它始终具有它所在的单元格所具有的水平-垂直比率,换句话说,它不会保持自己的比率 这是我的代码: titleRow = sheet.createRow(0); titleRow.setHeightInPoints(25f); titleRow.cr
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表示.xls,Calibri 11pt表示.xlsx)。如果 默认字体已更改,可以拉伸调整大小的图像 垂直或水平
我想你可以试着补充一下
anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
好的,谢谢你的回答。不过有一个问题,你知道我是如何设置默认字体的吗?我试着删除我使用过的所有字体规格,但没有任何区别。