2025 Java EasyExcel 基于Excel模板填充数据 SpringBoot+Mybatis-Flex

一、模版文件【仅供参考】

二、pom依赖

XML 复制代码
        <!--easyExcel-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.3.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-support</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!-- POI导入导出 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.1</version>
        </dependency>

三、逻辑代码【仅供参考】

java 复制代码
     /**
     * 导出数据
     *
     * @return 所有数据
     */
    @GetMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        //业务逻辑代码.....

        // 获取数据列表
        List<自己的实体类> exportDataList = 自己的Mapper.selectAll();

        // 6. 导出Excel
        exportToExcel(response, exportDataList, "示例表头标题", "示例文件名称");
    }

    /**
     * 导出数据到Excel
     *
     * @param response
     * @param data         导出的数据源
     * @param templateName 表头标题
     * @param fileName     文件名称
     * @throws IOException
     */
    private void exportToExcel(HttpServletResponse response, List<自己的实体类> data, String templateName, String fileName) throws IOException {
        InputStream templateFile = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("template/template.xlsx");

        ExcelWriter excelWriter = null;

        try {
            // 设置响应头
            setupResponseHeaders(response, fileName);

            excelWriter = EasyExcel.write(response.getOutputStream())
                    .withTemplate(templateFile)
                    .build();

            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
            // 构造标题填充数据
            Map<String, String> titleFillData = new HashMap<>();
            titleFillData.put("templateName", templateName);
            // 先填充标题占位符
            excelWriter.fill(titleFillData, writeSheet);
            // 填充数据
            excelWriter.fill(data, fillConfig, writeSheet);


        } catch (Exception e) {
            handleExportError(response, e);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            if (templateFile != null) {
                templateFile.close();
            }
        }
    }


    /**
     * 设置响应头
     *
     * @param response
     * @param fileName 文件名称
     * @throws IOException
     */
    private void setupResponseHeaders(HttpServletResponse response, String fileName)
            throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    /**
     * 处理导出错误
     */
    private void handleExportError(HttpServletResponse response, Exception e)
            throws IOException {
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, String> map = new HashMap<>();
        map.put("status", "failure");
        map.put("message", "下载文件失败: " + e.getMessage());
        response.getWriter().println(JSON.toJSONString(map));
    }

四、效果展示

相关推荐
有个傻瓜3 小时前
分页 total 对不上、列表还少几条:MyBatis-Plus 一对多 LEFT JOIN 分页错乱复盘与四种写法实测
spring boot·sql优化·mybatis-plus·分页查询·踩坑复盘
考虑考虑4 小时前
JDK27结构化并发
java·后端·java ee
Cosolar6 小时前
监控指标全正常,订单接口从 80ms 涨到 4s 故障复盘
java·后端·面试
千寻技术帮14 小时前
微信小程序+Spring Boot 烘焙商城系统(附完整源码+数据库+部署文档)50053
数据库·spring boot·微信小程序·烘焙商城
会编程的吕洞宾15 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤15 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
stormsha15 小时前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
SongRenShuo16 小时前
三年 MyBatis 排查史:从我翻日志,到让 SQL 自己浮现
sql·mybatis·idea·日志·调试
RobinXYuan16 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!16 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python