Easyexcel导出图片,固定单元格宽度自动高度保持图片比例
工作中有个导出需求,在导出的数据中有个图片。然后平常一直在使用 easyexcel,但在导出图片这块官方的案例中只是给出了
@ContentRowHeight(100) @ColumnWidth(100 / 8)
的方式进行设置,但我的每条数据图片比例可能存在差异,为了避免图片的比例失衡,找了个解决方法
灵感来源:如何根据单元格内容设置不同的样式?
这个Github上的一个issue,提到了使用 继承AbstractCellStyleStrategy 的方式来自定义单元格
并且你也能在源代码中,easyexcel-core
的 module 下的style包下找到一些 Strategy 类,这些源代码中带的样式策略,其中你能找到一个叫 LongestMatchColumnWidthStyleStrategy
的类。该类有个dataLength
方法,该方法便通过swith cell 类型判断来决定 cell 单元格的宽度,我们可以以此为思路修改下写一个自己的 Strategy。
该方法中的类型使用了 CellDataTypeEnum
枚举,但可以注意到该枚举中没有图片的类型,经过 debug 发现当单元格是图片时它会是 EMPTY
类型,且 imageDataList
属性可以看到我们塞进去的图片。有图片就能只能宽高,同时 Cell
类也能拿到单元行我也就能设置行高如下面的代码
switch (type) {
case STRING:
return cellData.getStringValue().getBytes().length;
case BOOLEAN:
return cellData.getBooleanValue().toString().getBytes().length;
case NUMBER:
return cellData.getNumberValue().toString().getBytes().length;
// 如果是图片返回图片的宽度,并设置row的高度为图片的高度
case EMPTY:
if (cellData.getImageDataList() != null && !cellData.getImageDataList().isEmpty()) {
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(cellData.getImageDataList().get(0).getImage()));
int originalWidth = bufferedImage.getWidth();
int originalHeight = bufferedImage.getHeight();
// 计算与210的宽度的比例
double ratio = (double) 210 / originalWidth;
int newWidth = 210; // 设置新宽度为210
int newHeight = (int) (originalHeight * ratio);
// 将像素转换为磅以设置Excel行高
double heightInPoints = newHeight * 0.75;
cell.getRow().setHeightInPoints((float) heightInPoints);
// 将像素转换为Excel中的宽度单位
double charWidth = 7.0; // 默认的Excel字体中标准字符的大致宽度
double estimatedChars = newWidth / charWidth;
return (int) estimatedChars; // 以Excel单位返回调整后的宽度
}
return -1;
default:
return -1;
}
210 是我想固定的图片像素宽度,最终宽度会被计算为单元格的宽度,而高度会被等比例计算为行上磅为单位的高度