java excel poi 图片大小_Apache POI Excel工作表:在保持比例的同时调整图片大小

使用Apache POI库在Java中处理Excel时,可以通过计算来调整图片大小以填充单元格并保持比例。通过设置XSSFClientAnchor,可以确保图片在不覆盖网格线的同时正确对齐。此过程涉及到对单元格宽度的计算,包括字符宽度、像素转换以及适当内边距的设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// Excel width, not character width

width = Truncate([{Number of Visible Characters} * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width} * 256)/256

以Calibri字体为例,11点字体大小的最大数字宽度为7像素(96 dpi)。如果您将列宽设置为八个字符宽度,例如setColumnWidth(columnIndex,8 * 256),则可见字符(在Excel中显示的值)的实际值从下式导出: Truncate([numChars * 7 + 5]/7 * 256)/256 = 8;

使用cmToW()当设置列的宽度(字符宽度 )如sheet.setColumnWidth()

下面我设置XSSFClientAnchor来调整图片以填充细胞并保持其比。 // set padding between picture and gridlines so gridlines would not covered by the picture

private static final double paddingSize = 10;

private static final int padding = Units.toEMU(paddingSize);

public static int[] calCellAnchor(double cellX, double cellY, int imgX, int imgY) {

// assume Y has fixed padding first

return calCoordinate(true, cellX, cellY, imgX, imgY);

}

public static int[] calCoordinate(boolean fixTop, double cellX, double cellY, int imgX, int imgY) {

int x = imgX;

double ratio = ((double) imgX)/imgY;

x = (int) Math.round(Units.toEMU(cellY - 2 * paddingSize) * ratio);

x = (Units.toEMU(cellX) - x)/2;

if (x < padding) {

return calCoordinate(false, cellY, cellX, imgY, imgX);

}

return calDirection(fixTop, x);

}

public static int[] calDirection(boolean fixTop, int x) {

if (fixTop) {

return new int[] { x, padding, -x, -padding };

} else {

return new int[] { padding, x, -padding, -x };

}

}

...

// set XSSFClientAnchor here

BufferedImage img = ImageIO.read(new File(path));

int[] anchorArray = calCellAnchor(Units.pixelToPoints(cellW), Units.pixelToPoints(cellH), img.getWidth(),

img.getHeight());

XSSFClientAnchor anchor = new XSSFClientAnchor(anchorArray[0], anchorArray[1], anchorArray[2], anchorArray[3], col1, row1, col2, row2);

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值