SpringBoot 将多个Excel打包下载

在Spring Boot应用中,如果你需要将多个Excel文件打包成一个ZIP文件并提供下载,你可以使用一些Java库来帮助完成这个任务。这里我将展示如何使用Apache POI来生成Excel文件,以及使用Java.util.zip来创建ZIP文件,并通过Spring Boot的控制器提供下载功能。

一、实现思路:

1.引入Apache POI坐标,用来生成Excel文件,引入Java.util.zip用来创建ZIP文件。

2.使用Apache POI将导出的Excel构造成byte[]。

3.使用util.zip将多个byte[]输出成压缩包。

二、实现步骤:

1. 添加依赖

首先,在你的pom.xml中添加必要的依赖:

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

    <!-- Apache POI for Excel generation -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version> <!-- 请检查最新版本 -->
    </dependency>
</dependencies>

2. 创建Excel文件

假设你已经有方法来生成Excel文件,如果没有,可以参考以下示例代码:

java 复制代码
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class ExcelGenerator {

    public static byte[] generateExcel(List<String[]> data) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        int rowNum = 0;
        for (String[] rowData : data) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (String cellData : rowData) {
                Cell cell = row.createCell(colNum++);
                cell.setCellValue(cellData);
            }
        }

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            workbook.write(out);
            return out.toByteArray();
        } finally {
            workbook.close();
        }
    }
}

3. 创建ZIP文件

使用java.util.zip来创建包含多个Excel文件的ZIP文件:

java 复制代码
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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 javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

    @GetMapping("/download-zip")
    public void downloadZip(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=excel_files.zip");

        // 创建ZIP输出流
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            // 假设我们有多个Excel数据列表
            List<List<String[]>> excelDataList = getExcelDataLists(); // 你需要实现这个方法

            for (int i = 0; i < excelDataList.size(); i++) {
                List<String[]> excelData = excelDataList.get(i);

                // 生成Excel文件内容
                byte[] excelBytes = ExcelGenerator.generateExcel(excelData);

                // 创建ZIP条目
                ZipEntry entry = new ZipEntry("file" + (i + 1) + ".xlsx");
                zos.putNextEntry(entry);

                // 写入Excel文件到ZIP条目
                zos.write(excelBytes);
                zos.closeEntry();
            }
        }
    }

    private List<List<String[]>> getExcelDataLists() {
        // 返回模拟的数据列表
        // 这里你需要根据实际情况返回实际的数据
        return List.of(
                List.of(new String[]{"Header1", "Header2"}, new String[]{"Data1", "Data2"}),
                List.of(new String[]{"HeaderA", "HeaderB"}, new String[]{"DataA", "DataB"})
        );
    }
}

4. 测试

启动Spring Boot应用后,访问/api/excel/download-zip端点,应该会触发下载一个名为excel_files.zip的ZIP文件,其中包含了多个Excel文件。

相关推荐
用户21411832636027 小时前
Qwen3-Coder 实战!历史人物短视频一键生成,多分镜人物不崩,魔搭直接玩
后端
追逐时光者7 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 54 期(2025年9.8-9.14)
后端·.net
追逐时光者7 小时前
C#/.NET/.NET Core编程技巧练习集,配套详细的文章教程讲解!
后端·.net
AD钙奶-lalala7 小时前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket
moxiaoran57538 小时前
Flask学习笔记(一)
后端·python·flask
你的人类朋友8 小时前
🔒什么是HMAC
后端·安全·程序员
毕设源码-朱学姐8 小时前
【开题答辩全过程】以 4S店汽车维修保养管理系统为例,包含答辩的问题和答案
java·spring boot·汽车
盖世英雄酱581369 小时前
Read timed out问题 排查
java·数据库·后端
BXCQ_xuan9 小时前
软件工程实践二:Spring Boot 知识回顾
java·spring boot·后端
o0o_-_9 小时前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang