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文件。

相关推荐
怒放吧德德8 分钟前
Spring Boot实战:InfluxDB 2.x简单教程
java·spring boot·后端
indexsunny11 分钟前
互联网大厂Java面试实战:核心技术与业务场景深度解析
java·spring boot·hibernate·security·microservices·interview
后端不背锅13 分钟前
可观测性体系:日志、指标、链路追踪
后端
苍何24 分钟前
把小度音箱接入小龙虾是一种什么体验?
后端
华科易迅42 分钟前
Spring AOP
java·后端·spring
架构师沉默1 小时前
Gemini 正式登陆香港,不用翻墙!
java·后端·架构
zihao_tom1 小时前
Spring WebFlux:响应式编程
java·后端·spring
想打游戏的程序猿1 小时前
从零理解 LLM 与 Agent
后端·ai编程
wooyoo1 小时前
花了一周 vibe 了一个 OpenClaw 的 Agent 市场,聊聊过程中踩的坑
前端·后端·agent
树獭叔叔2 小时前
文本Embedding模型演进:从Encoder-only到LLM-based的技术变革
后端·aigc·openai