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

相关推荐
间彧18 分钟前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
间彧24 分钟前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧35 分钟前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng42 分钟前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
用户0332126663671 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
间彧1 小时前
ThreadLocal实现原理与应用实践
java
若水不如远方2 小时前
Netty的四种零拷贝机制:深入原理与实战指南
java·netty
用户7493636848432 小时前
【开箱即用】一分钟使用java对接海外大模型gpt等对话模型,实现打字机效果
java
SimonKing2 小时前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员
间彧3 小时前
Spring Boot集成Spring Security 6.x完整指南
java