SpringBoot项目使用“EasyExcel”导出Excel数据

前有导入,同时就会伴有导出,那么导出来了。

直接进入正题:

第一步:导入EasyExcel的pom
properties标签下引入本人使用的是2.1.6版本鸭~
2.1.6
dependencies标签下引入

    com.alibaba
    easyexcel
    ${easyexcel.version}

到这里,准备工作就做好了,下面进行正式代码环节#

Controller层代码:

public void monitorPointDetailExport(HttpServletResponse response, String sheetName, String fileName, MonitorPointDetailQo monitorPointDetailQo) throws IOException {
    monitorPointService.monitorPointDetailExport(response, sheetName, fileName, monitorPointDetailQo);
}

Service层代码:

void monitorPointDetailExport(HttpServletResponse response, String sheetName, String fileName, MonitorPointDetailQo monitorPointDetailQo) throws IOException;

Impl层代码:

@Override
public void monitorPointDetailExport(HttpServletResponse response, String sheetName, String fileName, MonitorPointDetailQo monitorPointDetailQo) throws IOException {
    // 生成数据
    List respCustomerDailyImports = this.monitorPointDetailNoPage(monitorPointDetailQo);
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码
    fileName = URLEncoder.encode(fileName, "UTF-8");
    response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
    EasyExcel.write(response.getOutputStream(), MonitorPointDetailExportVo.class)
            .sheet(sheetName)
            .head(this.getMonitorPointDetailHead())
            // 设置字段宽度为自动调整
            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
            .doWrite(respCustomerDailyImports);
}

补充说明:导出的Excel内容的列顺序根据MonitorPointDetailExportVo这个Vo里面的字段决定。

无需多解释了,代码里面有注释,生成数据换成自己的,其他复制。

你可能感兴趣的:(spring,boot,java,mybatis)