假设需要导出的实体类为User,其中包含一个属性为image,类型为String,存储的是图片的base64编码。

  1. 首先需要将base64编码的字符串转换为图片,并放入一个临时文件中。
public static File base64ToFile(String base64String) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    File file = File.createTempFile("temp", ".jpg");
    try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write(bytes);
        fos.flush();
    }
    return file;
}
  1. 在实体类的image属性上添加@Excel注解,并设置imageType为2(表示图片类型),width和height分别为图片的宽度和高度。
public class User {
    @Excel(name = "图片", type = 2, width = 40, height = 20, imageType = 2)
    private String image;
    // ...
}
  1. 在导出Excel的代码中,获取图片文件并将其设置为单元格的值。
List<User> userList = getUserList(); // 获取要导出的数据列表

Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), User.class, userList);
Sheet sheet = workbook.getSheetAt(0);

for (int i = 1; i <= userList.size(); i++) {
    Row row = sheet.getRow(i);
    User user = userList.get(i - 1);
    String imageBase64 = user.getImage();
    if (StringUtils.isNotBlank(imageBase64)) {
        try {
            File imageFile = base64ToFile(imageBase64);
            Drawing patriarch = sheet.createDrawingPatriarch();
            ClientAnchor anchor = new XSSFClientAnchor();
            anchor.setCol1(0);
            anchor.setRow1(i);
            anchor.setCol2(1);
            anchor.setRow2(i + 1);
            anchor.setDx1(0);
            anchor.setDy1(0);
            anchor.setDx2(0);
            anchor.setDy2(0);
            Picture picture = patriarch.createPicture(anchor, workbook.addPicture(FileUtils.readFileToByteArray(imageFile), Workbook.PICTURE_TYPE_JPEG));
            picture.resize(1, 1);
            imageFile.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

workbook.write(new FileOutputStream("userList.xlsx"));
workbook.close();
``

原文地址: http://www.cveoy.top/t/topic/ci88 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录