使用 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 导出变得非常简单。希望这篇文章对大家有所帮助!

相关推荐
小小测试开发1 天前
安装 Python 3.10+
开发语言·人工智能·python
AAA大运重卡何师傅(专跑国道)1 天前
【无标题】
开发语言·c#
XBodhi.1 天前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
LSssT.1 天前
【01】Python 机器学习
开发语言·python
心之伊始1 天前
Java 后端接入大模型:从 Token、并发到推理成本的完整估算方法
java·spring boot·性能优化·大模型·llm
l1t1 天前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
BlackTurn1 天前
技术经理投标
java
曾阿伦1 天前
Python 搭建简易HTTP服务
开发语言·python·http
YG亲测源码屋1 天前
java配置环境变量、jdk环境变量配置、java环境变量设置方法
java·开发语言
MIUMIUKK1 天前
从语法层面,看懂 Python 的特殊处
java·开发语言·python