教你用EasyExcel导出包含图片列的excel

教你用EasyExcel导出包含图片列的excel

在这里插入图片描述

前情概要

众所周知,导入及导出功能在后台服务中很常见,博主目前参与的这个项目就有多Excel的导入和导出,但是在我昨天完成需求的时候,突然发现项目里目前的Excel工具类无法满足的我的业务需求。
所以在参考EasyExcel官方文档的情况下,昨天经历千辛万苦完成了Excel中某几列是图片的导出(原谅我是个菜b)。

正文来啦

首先需要导入EasyExcel的maven依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>${easyexcel.version}</version>
</dependency>

版本选最新的即可,我这里添加了版本的集中控制。

然后打开www.baidu.com搜索EasyExcel官方文档,找到快速开始写Excel那一栏:

这就是官方给我的demo,已经很详细了,然后我们找到图片导出这个功能:

根据文档提示,我们需要编写Excel对应的实体类:

@Data
@ContentRowHeight(15)
@HeadRowHeight(25)
@ColumnWidth(25)
@Accessors(chain = true)
public class ExportInspectionModel {
    
    

    /**
     * 检测名称
     */
    @ExcelProperty(value = "检验名称")
    private String inspectionName;

    /**
     * 施工单位
     */
    @ExcelProperty(value = "检验名称")
    private String constructionOrganization;
    /**
     * 见证人id
     */
    @ExcelProperty(value = "见证人")
    private String userName;


    /**
     * 检验类型:1:平行检验;2:见证检验。
     */
    @ExcelProperty(value = "检验类型")
    private String inspectionType;
    /**
     * 项目id
     */
    @ExcelProperty(value = "项目名称")
    private String projectName;
    /**
     * 检验报告url
     */
    @ExcelProperty(value = "报告",converter = UrlImageConverter.class)
    @ColumnWidth(60)
    private URL inspectionReportUrl;
    /**
     * 创建时间
     */
    @ExcelProperty(value = "创建时间",converter = LocalDateTimeConverterUtil.class)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;


然后就需要我们编写自己的业务数据查询逻辑了,如果只是普通的数据导出,可以不用像我这么复杂,直接把查询到的数据转换为ExcelModelList集合即可。然后调用:

ServletOutputStream outputStream = response.getOutputStream();
EasyExcel.write(outputStream, ExportInspectionModel.class).sheet().doWrite(excelModelList);

但是由于我这个需求导出数据列表包含图片,就不能这么操作了。
这是官方文档给出的5种数据格式的图片导出类型:

@Data
@ContentRowHeight(100)
@ColumnWidth(100 / 8)
public class ImageData {
    
    
    private File file;
    private InputStream inputStream;
    /**
     * 如果string类型 必须指定转换器,string默认转换成string
     */
    @ExcelProperty(converter = StringImageConverter.class)
    private String string;
    private byte[] byteArray;
    /**
     * 根据url导出
     *
     * @since 2.1.1
     */
    private URL url;
}

由于我们项目数据库保存的是图片的url,所以我选择了最后一种方式进行图片的导出,也就是根据URL导出。
在这里有一个注意点:实体类的图片url是String类型,需要转换为URL类型。

setInspectionReportUrl(new URL(experimentalInspection.getInspectionReportUrl()))

完成这些以后,就可以进行导出的测试了。这里是我进行测试的结果,就是图片宽高有点不合适,稍微调试即可。

Guess you like

Origin blog.csdn.net/Greenarrow961224/article/details/117765832