使用 Spring Boot 和 EasyExcel 进行动态表头导出 Excel

引言

在企业级应用中,经常需要将数据导出为 Excel 文件,以便用户进行分析和查看。Spring Boot 结合 EasyExcel 可以非常方便地实现这一需求。本文将详细介绍如何使用 Spring Boot 和 EasyExcel 进行动态表头的 Excel 导出。

环境准备

1. 添加依赖

首先,在 pom.xml 文件中添加 EasyExcel 和其他必要的依赖:

复制代码
<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- EasyExcel -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>3.2.1</version>
    </dependency>

    <!-- Hutool 工具类 -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.11</version>
    </dependency>
</dependencies>

2. 创建模板文件

在 src/main/resources/templates 目录下创建一个 Excel 模板文件 exportTemplate.xlsx,内容如下:

第二行

代码实现

1. 创建数据模型

定义一个数据模型类 DataModel,用于存储要导出的数据:

复制代码
package org.songtang.springbootdynamic.controller;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class DataModel {
    @ExcelProperty(index = 0)
    private Integer id;
    @ExcelProperty(index = 1)
    private String name;
    @ExcelProperty(index = 2)
    private String code;

    public DataModel(Integer id, String name, String code) {
        this.id = id;
        this.name = name;
        this.code = code;
    }
}

2. 创建控制器

在控制器中,我们将读取模板文件,填充动态表头和数据,然后将结果导出:

复制代码
package org.songtang.springbootdynamic.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    @GetMapping("/export")
    public ResponseEntity<byte[]> export() throws IOException {
        Resource resource = new ClassPathResource("templates/exportTemplate.xlsx");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        InputStream templateIs = resource.getInputStream();

        try (ExcelWriter excelWriter = EasyExcel.write(bos).withTemplate(templateIs).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            // 示例数据
            List<DataModel> dataList = new ArrayList<>();
            dataList.add(new DataModel(1, "张三", "A"));
            dataList.add(new DataModel(2, "李四", "B"));
            dataList.add(new DataModel(3, "王五", "C"));

            // 填充数据
            excelWriter.fill(dataList, writeSheet);

            // 动态表头
            Map<String, Object> map = new HashMap<>();
            map.put("dynamicHeader", "9月");

            // 填充动态表头
            excelWriter.fill(map, writeSheet);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        try {
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode("exportTemplate", "UTF-8") + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return ResponseEntity
                .ok()
                .headers(headers)
                .body(bos.toByteArray());
    }
}

3. 启动应用

启动 Spring Boot 应用,访问 http://localhost:8080/excel/export,你应该能够下载到一个 Excel 文件,其中包含动态设置的表头和具体的导出数据。

总结

通过本文的介绍,我们学习了如何使用 Spring Boot 和 EasyExcel 进行动态表头的 Excel 导出。EasyExcel 提供了强大的功能和简洁的 API,使得 Excel 导出变得非常简单。希望这篇文章对大家有所帮助!

相关推荐
知守观6 小时前
一个半天需求干了三天:代码腐化的五个信号与自查命令
java·后端·代码规范
代码山河6 小时前
Java学习路线图:2026年最新版,从入门到架构师
java·学习·架构·教程·面向对象·项目
anew___6 小时前
《从零手写操作系统 (30):环境变量与进程上下文——export/unset与继承语义》
java·开发语言·网络·jvm·算法
Cx330❀6 小时前
Qt 多线程深度解析:从底层原理到 UI 线程与同步实战
开发语言·qt·ui·搜索引擎·性能优化·图形渲染
jason成都6 小时前
rtklib_java项目新增模块:rtklib-research与rtklib-stream功能详解
java·gnss·rtklib·rtklib_java
谢亮_vipxieliang7 小时前
Go GMP调度模型——从原理到实战的完整指南
开发语言·网络·golang
endswel7 小时前
Spring bean 注册多种方式
java·后端·spring
鬼手点金7 小时前
opencode-性能优化建议
java·人工智能·git·自动化·nanogpt
聪明蛋子哟7 小时前
Python与Java双栈实战:手撸一个支持RAG与Tool Calling的高性能Agent框架
java·开发语言·python
谢亮_vipxieliang7 小时前
Go Context 控制协程生命周期
开发语言·golang