SpringBoot集成easyexcel实现动态模板导出

添加依赖

xml 复制代码
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>
            
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

查看easyexcel 开发文档,定义excel动态模板

根据自己需求:

单属性用{} + 属性名填充,列表属性用{.} + 属性名填充

代码实战

导入请求,Controller层:

java 复制代码
    @GetMapping("/export")
    @ApiOperation("导出盘库范围")
    public void export(@ApiParam("盘库任务id") String id, HttpServletResponse response) {
        storeInventoryTaskService.export(id, response);
    }

业务实现,主要是查询需导出的数据比较简单:主要,使用map设置属性,map键值与excel中属性名对应上

java 复制代码
    public void export(String id, HttpServletResponse response) {
        StoreInventoryTaskDetailVo taskInfo = taskInfo(id);
        List<InventoryListVo> vos = rangeInfo(id);
        Map<String, Object> map = new HashMap<>();
        map.put("inventoryNo", taskInfo.getInventoryNo());
        map.put("storeName", taskInfo.getStoreName());
        map.put("startTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, taskInfo.getStartTime()));
        map.put("endTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, taskInfo.getEndTime()));
        // 自增序号
        AtomicInteger idx = new AtomicInteger();
        vos.forEach(el -> el.setIdx(idx.incrementAndGet()));
        map.put("list", vos);
        try {
            TemplateExcelUtil.downLoadExcel("盘库工单" + taskInfo.getInventoryNo(), "盘库工单模板.xlsx", map, response);
        } catch (Exception e) {
            throw new ServiceException("导出盘库工单报错");
        }
    }

核心类

TemplateExcelUtil.downLoadExcel

根据模板名称获取输入流,输出流也为固定套路,同时设置导出excel文件名,其余代码基本和官方文档保持一致即可

java 复制代码
@Slf4j
public class TemplateExcelUtil {

    /**
     * 根据模板导出数据
     *
     * @param fileName   导出文件名
     * @param sourcePath resource/template文件夹下路径
     */
    public static void downLoadExcel(String fileName, String sourcePath, Map<String, Object> beanParams, HttpServletResponse response)
            throws Exception {
        try (OutputStream os = getOutputStream(fileName, response);
             InputStream is = TemplateExcelUtil.class.getClassLoader().getResourceAsStream("template/" + sourcePath);
             ExcelWriter excelWriter = EasyExcel.write(os).withTemplate(is).build()) {

            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(beanParams.get("list"), fillConfig, writeSheet);
            excelWriter.fill(beanParams, writeSheet);

            // 关闭流
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 导出文件时为Writer生成OutputStream.
     *
     * @param fileName 文件名
     * @param response response
     */
    private static OutputStream getOutputStream(String fileName,
                                                HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
}

经测试,导出效果如下:

相关推荐
shejizuopin6 分钟前
基于Spring Boot的高校科研管理系统的设计与实现(毕业论文)
java·spring boot·vue·毕业设计·论文·毕业论文·高校科研管理系统的设计与实现
indexsunny7 分钟前
互联网大厂Java面试实战:Spring Boot微服务在电商场景中的应用
java·数据库·spring boot·redis·微服务·kafka·电商
哪里不会点哪里.13 分钟前
如何自定义一个 Spring Boot Starter?
java·spring boot·后端
不吃香菜学java20 分钟前
springboot左脚踩右脚螺旋升天系列-入门程序
java·spring boot·后端
悟能不能悟31 分钟前
eclipse run springboot的application类,保存文件的路径会默认在哪里
java·spring boot·eclipse
没有bug.的程序员33 分钟前
Spring Boot 性能优化:启动时间从 5s 到 1s 的全链路实战指南
java·spring boot·后端·spring·性能优化·全链路·启动时间
Sweet锦40 分钟前
无需JVM!GraalVM打造Windows平台零依赖Java应用
java·windows·后端·云原生·开源
colicode44 分钟前
java短信接口开发对接全流程:Spring Boot项目集成短信功能详解
java·开发语言·spring boot
wasp5201 小时前
拒绝 OOM:Apache Fesod 高性能 Excel 处理架构全景解析
算法·架构·apache·excel
开开心心_Every1 小时前
电脑定时休息软件:久坐提醒养成活动习惯
游戏·微信·pdf·excel·语音识别·散列表·启发式算法