在 Spring Boot 中结合 EasyPoi @Excel 注解导出带图片的 Excel,需要先在实体类中添加图片字段,并使用 @Excel 注解进行配置,如下所示:

public class User {
    @Excel(name = 'ID')
    private Integer id;

    @Excel(name = '姓名')
    private String name;

    @Excel(name = '头像', type = 2, width = 20, height = 20, imageType = 2)
    private String avatar;
    
    // getter和setter省略
}

其中,@Excel 注解中的 type 属性表示该字段为图片类型,width 和 height 属性表示图片的宽度和高度,imageType 属性表示图片的类型,2 表示图片为 byte[] 类型。

接下来,可以在 Controller 中调用 EasyPoi 的 ExcelExportUtil.exportExcel 方法进行导出,如下所示:

@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
    List<User> userList = userService.getUserList();
    for (User user : userList) {
        // 加载图片并转为 byte[] 类型
        byte[] bytes = FileUtils.readFileToByteArray(new File(user.getAvatar()));
        user.setAvatar(new String(Base64.encodeBase64(bytes)));
    }
    // 导出 Excel
    ExcelExportUtil.exportExcel(new ExportParams('用户信息', '用户'), User.class, userList, new FileOutputStream('user.xlsx'));
    // 下载 Excel
    response.setContentType('application/octet-stream');
    response.setHeader('Content-Disposition', 'attachment; filename=user.xlsx');
    FileCopyUtils.copy(new FileInputStream('user.xlsx'), response.getOutputStream());
}

在导出 Excel 之前,需要将图片加载并转为 byte[] 类型,然后将 byte[] 类型的图片存入实体类中。导出 Excel 时,使用 ExcelExportUtil.exportExcel 方法进行导出,其中第一个参数为导出参数,第二个参数为实体类类型,第三个参数为数据列表,第四个参数为导出文件流。

最后,在 Controller 中设置响应头信息,将 Excel 文件通过响应输出流进行下载。

注意:在导出 Excel 时,需要先将图片转为 byte[] 类型,并存入实体类中,否则导出的 Excel 文件中无法正确显示图片。

Spring Boot EasyPoi 导出带图片 Excel:@Excel 注解 & 图片类型 imageType = 2

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

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