如何对我们导出的图片设置大小和位置
首先我们先丢入一张图片,这里我就直接通过URL的形式进行编写
定义一个存储图片的类
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;import java.net.URL;@Getter
@Setter
@EqualsAndHashCode
public class ImageDemoData {/*** 根据url导出**/private URL url;}
需要将图片插入的操作(把图片赛进List中)
ImageDemoData imageDemoData = new ImageDemoData();imageDemoData.setUrl(new URL("https://img-blog.csdnimg.cn/img_convert/ff9e522ef239408bb54947c4fe64ae0f.png?x-oss-process=image/resize,m_fixed,h_300,image/format,png"));List<ImageDemoData> imageDemoDataList = new ArrayList<>();imageDemoDataList.add(imageDemoData);
在ExcelWriter中对其进行写入操作
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
excelWriter.write(imageDemoDataList, writeSheet);
下面进入正题(以上操作很正常插入数据的操作是相同的)
package com.mixcloud.mall.ams.interceptor;import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.SneakyThrows;
import org.apache.commons.lang.BooleanUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFDrawing;import java.net.URL;
import java.util.List;public class QuotationCustomCellWriteHandler extends AbstractCellWriteHandler {private int newWidthEMU;private int newHeightEMU;public QuotationCustomCellWriteHandler(int newWidthPixels, int newHeightPixels) {this.newWidthEMU = newWidthPixels;this.newHeightEMU = newHeightPixels;}@Overridepublic void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {short height = 600;row.setHeight(height);}@SneakyThrows@Overridepublic void afterCellDispose(CellWriteHandlerContext context) {Cell cell = context.getCell();if (context.getOriginalValue().toString().contains("https://img-blog.csdnimg.cn/img_convert/ff9e522ef239408bb54947c4fe64ae0f.png?x-oss-process=image/resize,m_fixed,h_300,image/format,png")) {Sheet sheet = cell.getSheet();Drawing<?> drawingPatriarch = sheet.getDrawingPatriarch();if (drawingPatriarch instanceof XSSFDrawing) {XSSFDrawing xssfDrawing = (XSSFDrawing) drawingPatriarch;for (Shape shape : xssfDrawing.getShapes()) {if (shape instanceof Picture) {Picture picture = (Picture) shape;ClientAnchor anchor = picture.getClientAnchor();// 设置新的图片大小anchor.setDx1(newWidthEMU);anchor.setDy1(newHeightEMU);// 更新图片picture.resize();}}}}super.afterCellDispose(context);}}
这样拦截器就会在当中成功的调整图片的大小
补充:调整位置只需要对anchor进行设置即可,例如下面代码
// 调整图片的行位置
int newRow1 = anchor.getRow1() - 2; // 向上移动两行
int newRow2 = anchor.getRow2() - 2; // 向上移动两行// 设置新的行位置
anchor.setRow1(newRow1);
anchor.setRow2(newRow2);
即可对图片进行自由调整