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

相关推荐
AI进化营-智能译站1 天前
ROS2 C++开发系列17-多线程驱动多传感器|chrono高精度计时实现机器人同步控制
java·c++·ai·机器人
天若有情6731 天前
程序员原创|借鉴JS事件冒泡,根治电脑文件混乱的“冒泡整理法”
开发语言·javascript·windows·ecmascript·电脑·办公·日常
qq_589568101 天前
springbootweb案例,出现访问 http://localhost:8080/list 一直处于浏览器运转阶段
java·网络协议·http·list·springboot
JAVA面经实录9171 天前
计算机基础(完整版·超详细可背诵)
java·linux·数据结构·算法
特种加菲猫1 天前
继承,一场跨越时空的对话
开发语言·c++
AC赳赳老秦1 天前
知识产权辅助:用 OpenClaw 批量生成专利交底书 / 软著申请材料,自动校验格式与内容合规性
java·人工智能·python·算法·elasticsearch·deepseek·openclaw
FYKJ_20101 天前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
玩转单片机与嵌入式1 天前
玩转边缘AI(TInyML):需要掌握的C++知识汇总!
开发语言·c++·人工智能
茉莉玫瑰花茶1 天前
Qt 信号与槽 [ 1 ]
开发语言·数据库·qt