Spring Boot 使用 EasyPoi @Excel 注解导出带图片的 Excel (图片来自数据库字节流)
- 首先,在实体类中添加一个字段,用于存储图片的字节字符串:
public class User {
@Excel(name = '头像', type = 2, width = 40, height = 20, imageType = ImageType.PNG)
private String avatar;
// 省略其他字段和getter/setter方法
}
其中,@Excel 注解中的 type 表示图片类型,2 表示导出图片;width 和 height 表示图片的宽度和高度;imageType 表示图片格式,这里使用 PNG 格式。
- 在导出 excel 的方法中,使用 EasyPoi 的
ExcelExportUtil.exportExcel方法导出 excel,并在其中使用ImageBytesPropertyHandler将图片字节字符串转换成图片。
@RequestMapping("/export")
public void export(HttpServletResponse response) throws Exception {
List<User> userList = userService.getUserList();
List<UserDto> userDtoList = BeanUtil.copyList(userList, UserDto.class);
// 将字节字符串转换成图片
ImageBytesPropertyHandler avatarHandler = new ImageBytesPropertyHandler();
avatarHandler.setImageType(ImageType.PNG);
avatarHandler.setStartRow(3);
avatarHandler.setEndRow(userDtoList.size() + 2);
avatarHandler.setImageBasePath("");
avatarHandler.setImageUrl("");
// 导出 excel
ExcelExportUtil.exportExcel(new ExportParams("用户列表", "用户"), UserDto.class, userDtoList,
avatarHandler, response, ExcelType.XLSX);
}
其中,ImageBytesPropertyHandler 是 EasyPoi 提供的一个类,用于将字节字符串转换成图片,我们需要设置好图片的类型、起始行、结束行、图片路径等属性。
- 最后,在
UserDto中添加一个avatar字段,用于保存图片的字节流。
public class UserDto {
@Excel(name = '头像', type = 2, width = 40, height = 20, imageType = ImageType.PNG)
private byte[] avatar;
// 省略其他字段和getter/setter方法
}
这样,我们就可以在导出 excel 时将数据库中的图片字节字符串转换成图片,并导出到 excel 中了。
原文地址: https://www.cveoy.top/t/topic/lXno 著作权归作者所有。请勿转载和采集!