目前使用的是easyexcel模板导出,网上找了一大圈并没有找到填充图片并保持图片原比例的方式,并且easyexcel模板导出貌似也没有直接调整图片大小的方式。
正当我一筹莫展之际发现了这篇博客:EasyExcel根据自定义模板导出Excel(包含图片、表格)
从这篇博客里发现可以通过调整图片和单元格的边距从而间接达到调整图片大小的目的,通过图片比例进一步计算可以达到让图片等比例缩小放置在单元格下的效果,代码如下:
public void test(){
Map<String, Object> map = new HashMap<>();
InputStream is = null;
try{
//获取模板文件输入流
is = new FileInputStream("youTamplatePath\\TestTamplate.xlsx");
//定义excel文件输出位置以及文件名
String fileName = "youpath\\demo.xlsx";
//获取图片文件
File inputFile = new File("youImgPath\\1697022171707.png");
//获取图片宽高,用以计算比例
BufferedImage image = ImageIO.read(inputFile);
Double width = Double.valueOf(image.getWidth());
Double height = Double.valueOf(image.getHeight());
//自定义方法,用于处理图片在单元格内大小并达到等比例调整的效果
WriteCellData<Void> voidWriteCellData = TemplateExcelUtils.imageCells(FileUtils.getBytes(inputFile),width,height,2.37,3.82,0,1);
map.put("img",voidWriteCellData);
ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.fill(map,writeSheet);
excelWriter.finish();
}catch(Exception e){
e.printStackTrace();
}finally {
if(is != null){
try{
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
自定义工具类中imageCells方法代码:
//参数依次为图片字节,图片宽度(像素),图片高度,行高(厘米,多个单元格合并后的值),列宽(厘米,多个单元格合并后的值),行偏移量,列偏移量
public static WriteCellData<Void> imageCells(byte[] bytes,Double imageWidth,Double imageHight,Double rowLength,Double columLength,Integer lastRowIndex,Integer lastColumnIndex) throws IOException {
//等比例缩小图片,直到图片能放在单元格下,每次缩小20%
Integer top = 0;
Integer left = 0;
//厘米转换成像素,按实际需求转换
rowLength = rowLength*28;
columLength = columLength*28;
while (true){
if(imageHight <= rowLength && imageWidth <= columLength){
//计算边框值
top = Math.toIntExact(Math.round((rowLength - imageHight)/2));
left = Math.toIntExact(Math.round((columLength - imageWidth)/2));
break;
}else {
imageHight = imageHight*0.8;
imageWidth = imageWidth*0.8;
}
}
WriteCellData<Void> writeCellData = new WriteCellData<>();
// 这里可以设置为 EMPTY 则代表不需要其他数据了
// 可以放入多个图片,目前只放一张
List<ImageData> imageDataList = new ArrayList<>();
writeCellData.setImageDataList(imageDataList);
ImageData imageData = new ImageData();
imageDataList.add(imageData);
// 设置图片
imageData.setImage(bytes);
// 上右下左需要留空,通过这种方式调整图片大小,单位为像素
imageData.setTop(top);
imageData.setRight(left);
imageData.setBottom(top);
imageData.setLeft(left);
//以下四个属性分别为设置单元格偏移量,因为图片可能占据多个单元格(合并单元格)
// 这里我以左上角单元格为起始,所以FirstRowIndex和FirstColumnIndex默认为0
// 向右增加一格则设置LastColumnIndex为1,
// 向下增加一格设置LastRowIndex属性为1,
imageData.setRelativeFirstRowIndex(0);
imageData.setRelativeFirstColumnIndex(0);
imageData.setRelativeLastRowIndex(lastRowIndex);
imageData.setRelativeLastColumnIndex(lastColumnIndex);
return writeCellData;
}
以下为原图:
导出后效果: