使用 Easypoi 4.4.0 版本导出 Excel 带图片(Base64 编码)

本文将介绍如何使用 Easypoi 4.4.0 版本导出 Excel,并包含从数据库获取的 Base64 编码的图片。示例代码演示了如何将 Base64 编码转换为图片文件,并将其嵌入 Excel 中。

假设需要导出的实体类为 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;
}

2. 在实体类的 image 属性上添加 @Excel 注解,并设置 imageType 为 2(表示图片类型),widthheight 分别为图片的宽度和高度。

public class User {
    @Excel(name = '图片', type = 2, width = 40, height = 20, imageType = 2)
    private String image;
    // ...
}

3. 在导出 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();

注意:

  • 确保 easypoi 依赖已经添加到项目中。
  • base64ToFile 方法需要根据实际情况修改图片文件的后缀名。
  • 图片的宽度和高度可以根据实际需求调整。
  • 导出 Excel 文件的路径需要根据实际情况修改。
  • 代码中的 StringUtils 类来自 Apache Commons Lang 库,需要添加依赖。
  • 代码中使用的是 XSSFClientAnchor,适用于 xlsx 文件,如果需要导出 xls 文件,需要使用 HSSFClientAnchor
  • 图片在 Excel 中的显示效果可能与原始图片略有差异,建议在导出之前调整图片大小和格式。

希望这篇文章能够帮助您使用 Easypoi 导出包含 Base64 编码图片的 Excel 文件。

Easypoi 4.4.0 导出 Excel 带图片(Base64 编码)

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

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