SpringBoot 导出多个Excel文件,压缩成.zip格式下载

简介: SpringBoot 导出多个Excel文件,压缩成.zip格式下载

前言



之前写过一篇极其简单的excel导入导出,是单个文件的:


Springboot 最简单的结合MYSQL数据实现EXCEL表格导出及数据导入_小目标青年的博客-CSDN博客


还有指定模板的:


Springboot 指定自定义模板导出Excel文件_小目标青年的博客-CSDN博客


今天有人问到,多个文件导出,放到zip压缩包里面怎么搞?image.png


不多说,开搞。


正文



三步:


1. 引入 核心依赖

2. 复制粘贴已经给你们写好的工具类

3. 送一步,自测看效果


第一步,引依赖


<!-- 导入和导出-->

<dependency>

   <groupId>cn.afterturn</groupId>

   <artifactId>easypoi-base</artifactId>

   <version>3.0.3</version>

</dependency>

<dependency>

   <groupId>cn.afterturn</groupId>

   <artifactId>easypoi-web</artifactId>

   <version>3.0.3</version>

</dependency>

<dependency>

   <groupId>cn.afterturn</groupId>

   <artifactId>easypoi-annotation</artifactId>

   <version>3.0.3</version>

</dependency>


第二步,加工具类


ExcelUtil.java


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
/**
 * @Author: JCccc
 * @Date: 2022-7-13 16:02
 * @Description: excel工具类
 */
public class ExcelUtil {
    /**
     * 导出
     * @param list
     * @param title
     * @param sheetName
     * @param pojoClass
     * @param fileName
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    /**
     * 导出excle转换成 bytes
     * @param list
     * @param title
     * @param sheetName
     * @param pojoClass
     * @param fileName
     * @param response
     * @return
     * @throws IOException
     */
    public static byte[] getExportExcelBytes(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), pojoClass, list);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        return os.toByteArray();
    }
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}


ZipUtils.java


import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.springframework.util.StreamUtils.BUFFER_SIZE;
/**
 * @Author: JCccc
 * @Date: 2022-7-13 16:02
 * @Description: zip工具类
 */
public class ZipUtils {
    /**
     * 传入文件file
     * @param outputStream
     * @param fileList
     */
    public static void downloadZipForFiles(OutputStream outputStream, List<File> fileList){
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(outputStream);
            for (File file : fileList) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] buf = new byte[BUFFER_SIZE];
                int len;
                FileInputStream in = new FileInputStream(file);
                while ((len = in.read(buf)) != -1) {
                    zipOutputStream.write(buf, 0, len);
                    zipOutputStream.flush();
                }
            }
            zipOutputStream.flush();
            zipOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (zipOutputStream != null ) {
                    zipOutputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 传入文件的 byte[]
     * Map<String,byte[]> fileBufMap key是文件名(包含后缀),value是文件的byte[]
     * @param outputStream
     * @param fileBufMap
     */
    public static void downloadZipForByteMore(OutputStream outputStream,Map<String,byte[]> fileBufMap)  {
            ZipOutputStream zipOutputStream = null;
            try {
                zipOutputStream = new ZipOutputStream(outputStream);
                for (String fileName:fileBufMap.keySet()){
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zipOutputStream.putNextEntry(zipEntry);
                    if (Objects.nonNull(fileBufMap.get(fileName))){
                        byte[] fileBytes = fileBufMap.get(fileName);
                        zipOutputStream.write(fileBytes);
                        zipOutputStream.flush();
                    }
                }
                zipOutputStream.flush();
                zipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                // 关闭流
                try {
                    if (zipOutputStream != null ) {
                        zipOutputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
    /**
     * 返回zip包的 byte[]
     *
     * @param fileBufMap
     * @return
     */
    public static byte[] getZipForByteMore(Map<String,byte[]> fileBufMap)  {
        ByteArrayOutputStream totalZipBytes = null;
        ZipOutputStream zipOutputStream = null;
        try {
            totalZipBytes = new ByteArrayOutputStream();
            zipOutputStream = new ZipOutputStream(totalZipBytes);
            for (String fileName:fileBufMap.keySet()){
                ZipEntry zipEntry = new ZipEntry(fileName);
                zipOutputStream.putNextEntry(zipEntry);
                if (Objects.nonNull(fileBufMap.get(fileName))){
                    byte[] fileBytes = fileBufMap.get(fileName);
                    zipOutputStream.write(fileBytes);
                    zipOutputStream.flush();
                }
            }
            zipOutputStream.close();
            byte[] bytes = totalZipBytes.toByteArray();
            totalZipBytes.close();// 关闭流
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (totalZipBytes != null) {
                    totalZipBytes.close();
                }
                if (zipOutputStream != null) {
                    zipOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}


第三步,使用工具类,看看效果


回顾一下,单个excel导出,写过使用场景接口:


 

    @RequestMapping("exportUserExcel")
    public void exportUserExcel(HttpServletResponse response){
       // List<User> userList = userService.queryUserInfo();
        List<User> userList=new ArrayList<>();
        User user1=new User(1,"a","12");
        User user2=new User(1,"b","12");
        User user3=new User(1,"c","12");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        //导出操作
        ExcelUtil.exportExcel(userList,"用户信息","sheet1",User.class,"users.xls",response);
    }


调用一下:


image.png


多个文件导出,zip方式下载:


① 已经知道存在的文件路径

image.png


接口使用代码:


    /**
     * 将指定文件打包成zip并下载
     */
    @RequestMapping("exportExcelZipWithFile")
    public void exportExcelZipWithFile(HttpServletResponse response) throws IOException {
        // 这里还是和上面一样
        String[] filePath = new String[]{"D:\\ziptest\\11.xls", "D:\\ziptest\\22.xls"};
        List<File> fileList = new ArrayList<>();
        for (String s : filePath) {
            File file = new File(s);
            fileList.add(file);
        }
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=configDetail.zip");
        ZipUtils.downloadZipForFiles(response.getOutputStream(), fileList);
    }


效果:


image.pngimage.png


②直接生成excel,转换成byte再导出zip


    /**
     * 将excel文件的Byte[]打包成zip并下载
     */
    @RequestMapping("exportExcelZipWithByte")
    public void exportExcelZipWithByte(HttpServletResponse response) throws IOException {
        Map<String,byte[]> fileBufMap=new HashMap<>();
        List<Account> accountList=new ArrayList<>();
        Account account1=new Account(1,"1234");
        Account account2=new Account(2,"12222");
        Account account3=new Account(3,"1431546");
        accountList.add(account1);
        accountList.add(account2);
        accountList.add(account3);
        //导出操作 1
        byte[] exportAccountExcelBytes = ExcelUtil.getExportExcelBytes(accountList, "账号信息", "sheet1", Account.class, "accounts.xls", response);
        List<User> userList=new ArrayList<>();
        User user1=new User(1,"a","12");
        User user2=new User(1,"b","12");
        User user3=new User(1,"c","12");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        //导出操作
        byte[] exportUserExcelBytes =   ExcelUtil.getExportExcelBytes(userList,"用户信息","sheet1",User.class,"users.xls",response);
        fileBufMap.put("accounts.xls",exportAccountExcelBytes);
        fileBufMap.put("users.xls",exportUserExcelBytes);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=configDetail.zip");
        ZipUtils.downloadZipForByteMore(response.getOutputStream(), fileBufMap);
    }


代码简析:


这个map,key 是zip压缩包里面的文件名, vlaue是 excel文件的字节流:


image.png 


生成excel文件,我们直接返回 byte[]流:


image.pngimage.png


把多份excel文件的byte[] 都丢到map里面:


image.png


把每一个excel文件的 byte[]都放入 zip流:


image.png


实现效果:


image.png


好吧,该篇就到这。

相关文章
|
8月前
|
XML 前端开发 Java
SpringBoot实现文件上传下载功能
本文介绍了如何使用SpringBoot实现文件上传与下载功能,涵盖配置和代码实现。包括Maven依赖配置(如`spring-boot-starter-web`和`spring-boot-starter-thymeleaf`)、前端HTML页面设计、WebConfig路径映射配置、YAML文件路径设置,以及核心的文件上传(通过`MultipartFile`处理)和下载(利用`ResponseEntity`返回文件流)功能的Java代码实现。文章由Colorful_WP撰写,内容详实,适合开发者学习参考。
834 0
|
5月前
|
Python
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
7月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
396 10
|
12月前
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
2865 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
10月前
|
文字识别 Serverless 开发工具
【全自动改PDF名】批量OCR识别提取PDF自定义指定区域内容保存到 Excel 以及根据PDF文件内容的标题来批量重命名
学校和教育机构常需处理成绩单、报名表等PDF文件。通过OCR技术,可自动提取学生信息并录入Excel,便于统计分析和存档管理。本文介绍使用阿里云服务实现批量OCR识别、内容提取、重命名及导出表格的完整步骤,包括开通相关服务、编写代码、部署函数计算和设置自动化触发器等。提供Python示例代码和详细操作指南,帮助用户高效处理PDF文件。 链接: - 百度网盘:[链接](https://pan.baidu.com/s/1mWsg7mDZq2pZ8xdKzdn5Hg?pwd=8866) - 腾讯网盘:[链接](https://share.weiyun.com/a77jklXK)
1507 5
|
Python
批量将不同的工作簿合并到同一个Excel文件
本文介绍如何使用Python的`pandas`库批量合并不同工作簿至同一Excel文件。通过模拟生成三个班级的成绩数据,分别保存为Excel文件,再将这些文件合并成一个包含所有班级成绩的总成绩单。步骤包括安装必要库、生成数据、保存与合并工作簿。
391 6
|
Python
按条件将Excel文件拆分到不同的工作表
使用Python的pandas库,可以轻松将Excel文件按条件拆分为多个工作表。本文通过一个具体示例,展示了如何根据学生班级将成绩数据拆分到不同的工作表中,并生成一个包含总成绩表和各班级成绩表的Excel文件。代码简洁明了,适合初学者学习和应用。
413 6
|
Java easyexcel 应用服务中间件
【二十五】springboot使用EasyExcel和线程池实现多线程导入Excel数据
【二十五】springboot使用EasyExcel和线程池实现多线程导入Excel数据
1666 0
|
Java 关系型数据库 MySQL
java入门019~springboot批量导入excel数据到mysql
java入门019~springboot批量导入excel数据到mysql
379 0
Springboot 获取导入的Excel文件的sheet表 列名
Springboot 获取导入的Excel文件的sheet表 列名
342 0
Springboot 获取导入的Excel文件的sheet表 列名

热门文章

最新文章