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


好吧,该篇就到这。

相关文章
|
2月前
|
XML 前端开发 Java
基于SpringBoot 3.3实现任意文件在线预览功能的技术分享
【8月更文挑战第30天】在当今的数字化办公环境中,文件在线预览已成为提升工作效率、优化用户体验的重要功能之一。无论是文档、图片、PDF还是代码文件,用户都期望能够直接在浏览器中快速查看而无需下载。本文将围绕如何在Spring Boot 3.3框架下实现这一功能,分享一系列技术干货,助力开发者高效构建文件预览服务。
150 2
|
2天前
|
Java 关系型数据库 数据库连接
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第3天】Spring Boot项目中数据库连接问题可能源于配置错误或依赖缺失。YAML配置文件的格式不正确,如缩进错误,会导致解析失败;而数据库驱动不匹配、连接字符串或认证信息错误同样引发连接异常。解决方法包括检查并修正YAML格式,确认配置属性无误,以及添加正确的数据库驱动依赖。利用日志记录和异常信息分析可辅助问题排查。
22 10
|
4天前
|
存储 前端开发 Java
Spring Boot 集成 MinIO 与 KKFile 实现文件预览功能
本文详细介绍如何在Spring Boot项目中集成MinIO对象存储系统与KKFileView文件预览工具,实现文件上传及在线预览功能。首先搭建MinIO服务器,并在Spring Boot中配置MinIO SDK进行文件管理;接着通过KKFileView提供文件预览服务,最终实现文档管理系统的高效文件处理能力。
|
5天前
|
前端开发 Java easyexcel
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
14 6
|
1天前
|
Java 关系型数据库 MySQL
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第4天】本文分析了Spring Boot应用在连接数据库时可能遇到的问题及其解决方案。主要从四个方面探讨:配置文件格式错误、依赖缺失或版本不兼容、数据库服务问题、配置属性未正确注入。针对这些问题,提供了详细的检查方法和调试技巧,如检查YAML格式、验证依赖版本、确认数据库服务状态及用户权限,并通过日志和断点调试定位问题。
|
6天前
|
Java
SpringBoot获取文件将要上传的IP地址
SpringBoot获取文件将要上传的IP地址
21 6
|
2月前
|
Java Linux C++
【Azure 应用服务】App Service For Linux 部署Java Spring Boot应用后,查看日志文件时的疑惑
【Azure 应用服务】App Service For Linux 部署Java Spring Boot应用后,查看日志文件时的疑惑
|
存储 前端开发 Java
SpringBoot文件上传和下载
SpringBoot文件上传和下载
SpringBoot文件上传和下载
|
前端开发 Java Spring
SpringBoot文件上传下载
SpringBoot文件上传下载
244 0
SpringBoot文件上传下载
|
Java
SpringBoot文件上传下载
项目中经常会有上传和下载的需求,这篇文章简述一下springboot项目中实现简单的上传和下载。 新建springboot项目,前台页面使用的thymeleaf模板,其余的没有特别的配置,pom代码如下: 4.
4140 0
下一篇
无影云桌面