gpt4 book ai didi

java - 使用 POI 在 Excel 中拉伸(stretch)图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:06 25 4
gpt4 key购买 nike

在我的应用程序中,我使用 POI API 生成了一个 Excel 文件。文档左上角的一个单元格包含一张图像。我遇到的问题是图像被拉伸(stretch)以填充容纳它的单元格。

根据我在 Picture 对象上使用的调整大小方法,图像以各种尺寸显示,但它始终具有它所在的单元格所具有的水平垂直比例,换句话说,它不会保持自己的比例.

这是我的代码:

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;

有谁知道有什么办法可以避免这个问题,让图片保持原来的比例吗?

最佳答案

documentation 中有一点警告.

void resize()

Reset the image to the original size.

Please note, that this method works correctly only for workbooks with default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). If the default font is changed the resized image can be streched vertically or horizontally.

关于java - 使用 POI 在 Excel 中拉伸(stretch)图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8182689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com