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


    前言


    之前写过一篇极其简单的excel导入导出,是单个文件的:
    Springboot 最简单的结合MYSQL数据实现EXCEL表格导出及数据导入_小目标青年的博客-CSDN博客

    还有指定模板的: 

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

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

    不多说,开搞。

    正文 

    三步:

    1. 引入 核心依赖

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

    3. 送一步,自测看效果

    第一步,引依赖

    
    
        cn.afterturn
        easypoi-base
        3.0.3
    
    
        cn.afterturn
        easypoi-web
        3.0.3
    
    
        cn.afterturn
        easypoi-annotation
        3.0.3
    

    第二步,加工具类

    ExcelUtil.java

    1. import cn.afterturn.easypoi.excel.ExcelExportUtil;
    2. import cn.afterturn.easypoi.excel.entity.ExportParams;
    3. import org.apache.poi.ss.usermodel.Workbook;
    4. import javax.servlet.http.HttpServletResponse;
    5. import java.io.ByteArrayOutputStream;
    6. import java.io.IOException;
    7. import java.net.URLEncoder;
    8. import java.util.List;
    9. /**
    10. * @Author: JCccc
    11. * @Date: 2022-7-13 16:02
    12. * @Description: excel工具类
    13. */
    14. public class ExcelUtil {
    15. /**
    16. * 导出
    17. * @param list
    18. * @param title
    19. * @param sheetName
    20. * @param pojoClass
    21. * @param fileName
    22. * @param response
    23. */
    24. public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName, HttpServletResponse response) {
    25. defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    26. }
    27. /**
    28. * 导出excle转换成 bytes
    29. * @param list
    30. * @param title
    31. * @param sheetName
    32. * @param pojoClass
    33. * @param fileName
    34. * @param response
    35. * @return
    36. * @throws IOException
    37. */
    38. public static byte[] getExportExcelBytes(List list, String title, String sheetName, Class pojoClass, String fileName, HttpServletResponse response) throws IOException {
    39. Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), pojoClass, list);
    40. ByteArrayOutputStream os = new ByteArrayOutputStream();
    41. workbook.write(os);
    42. return os.toByteArray();
    43. }
    44. private static void defaultExport(List list, Class pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
    45. Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
    46. downLoadExcel(fileName, response, workbook);
    47. }
    48. private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
    49. try {
    50. response.setCharacterEncoding("UTF-8");
    51. response.setHeader("content-Type", "application/vnd.ms-excel");
    52. response.setHeader("Content-Disposition",
    53. "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    54. workbook.write(response.getOutputStream());
    55. } catch (IOException e) {
    56. throw new RuntimeException(e.getMessage());
    57. }
    58. }
    59. }

    ZipUtils.java

    1. import java.io.*;
    2. import java.util.List;
    3. import java.util.Map;
    4. import java.util.Objects;
    5. import java.util.zip.ZipEntry;
    6. import java.util.zip.ZipOutputStream;
    7. import static org.springframework.util.StreamUtils.BUFFER_SIZE;
    8. /**
    9. * @Author: JCccc
    10. * @Date: 2022-7-13 16:02
    11. * @Description: zip工具类
    12. */
    13. public class ZipUtils {
    14. /**
    15. * 传入文件file
    16. * @param outputStream
    17. * @param fileList
    18. */
    19. public static void downloadZipForFiles(OutputStream outputStream, List fileList){
    20. ZipOutputStream zipOutputStream = null;
    21. try {
    22. zipOutputStream = new ZipOutputStream(outputStream);
    23. for (File file : fileList) {
    24. ZipEntry zipEntry = new ZipEntry(file.getName());
    25. zipOutputStream.putNextEntry(zipEntry);
    26. byte[] buf = new byte[BUFFER_SIZE];
    27. int len;
    28. FileInputStream in = new FileInputStream(file);
    29. while ((len = in.read(buf)) != -1) {
    30. zipOutputStream.write(buf, 0, len);
    31. zipOutputStream.flush();
    32. }
    33. }
    34. zipOutputStream.flush();
    35. zipOutputStream.close();
    36. } catch (IOException e) {
    37. e.printStackTrace();
    38. } finally {
    39. // 关闭流
    40. try {
    41. if (zipOutputStream != null ) {
    42. zipOutputStream.close();
    43. }
    44. if (outputStream != null) {
    45. outputStream.close();
    46. }
    47. } catch (IOException e) {
    48. e.printStackTrace();
    49. }
    50. }
    51. }
    52. /**
    53. * 传入文件的 byte[]
    54. * Map fileBufMap key是文件名(包含后缀),value是文件的byte[]
    55. * @param outputStream
    56. * @param fileBufMap
    57. */
    58. public static void downloadZipForByteMore(OutputStream outputStream,Mapbyte[]> fileBufMap) {
    59. ZipOutputStream zipOutputStream = null;
    60. try {
    61. zipOutputStream = new ZipOutputStream(outputStream);
    62. for (String fileName:fileBufMap.keySet()){
    63. ZipEntry zipEntry = new ZipEntry(fileName);
    64. zipOutputStream.putNextEntry(zipEntry);
    65. if (Objects.nonNull(fileBufMap.get(fileName))){
    66. byte[] fileBytes = fileBufMap.get(fileName);
    67. zipOutputStream.write(fileBytes);
    68. zipOutputStream.flush();
    69. }
    70. }
    71. zipOutputStream.flush();
    72. zipOutputStream.close();
    73. } catch (IOException e) {
    74. e.printStackTrace();
    75. }finally {
    76. // 关闭流
    77. try {
    78. if (zipOutputStream != null ) {
    79. zipOutputStream.close();
    80. }
    81. if (outputStream != null) {
    82. outputStream.close();
    83. }
    84. } catch (IOException e) {
    85. e.printStackTrace();
    86. }
    87. }
    88. }
    89. /**
    90. * 返回zip包的 byte[]
    91. *
    92. * @param fileBufMap
    93. * @return
    94. */
    95. public static byte[] getZipForByteMore(Mapbyte[]> fileBufMap) {
    96. ByteArrayOutputStream totalZipBytes = null;
    97. ZipOutputStream zipOutputStream = null;
    98. try {
    99. totalZipBytes = new ByteArrayOutputStream();
    100. zipOutputStream = new ZipOutputStream(totalZipBytes);
    101. for (String fileName:fileBufMap.keySet()){
    102. ZipEntry zipEntry = new ZipEntry(fileName);
    103. zipOutputStream.putNextEntry(zipEntry);
    104. if (Objects.nonNull(fileBufMap.get(fileName))){
    105. byte[] fileBytes = fileBufMap.get(fileName);
    106. zipOutputStream.write(fileBytes);
    107. zipOutputStream.flush();
    108. }
    109. }
    110. zipOutputStream.close();
    111. byte[] bytes = totalZipBytes.toByteArray();
    112. totalZipBytes.close();// 关闭流
    113. return bytes;
    114. } catch (IOException e) {
    115. e.printStackTrace();
    116. } finally {
    117. // 关闭流
    118. try {
    119. if (totalZipBytes != null) {
    120. totalZipBytes.close();
    121. }
    122. if (zipOutputStream != null) {
    123. zipOutputStream.close();
    124. }
    125. } catch (IOException e) {
    126. e.printStackTrace();
    127. }
    128. }
    129. return null;
    130. }
    131. }

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

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

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

    调用一下:

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

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

    接口使用代码: 

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

    效果:

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

    1. /**
    2. * 将excel文件的Byte[]打包成zip并下载
    3. */
    4. @RequestMapping("exportExcelZipWithByte")
    5. public void exportExcelZipWithByte(HttpServletResponse response) throws IOException {
    6. Mapbyte[]> fileBufMap=new HashMap<>();
    7. List accountList=new ArrayList<>();
    8. Account account1=new Account(1,"1234");
    9. Account account2=new Account(2,"12222");
    10. Account account3=new Account(3,"1431546");
    11. accountList.add(account1);
    12. accountList.add(account2);
    13. accountList.add(account3);
    14. //导出操作 1
    15. byte[] exportAccountExcelBytes = ExcelUtil.getExportExcelBytes(accountList, "账号信息", "sheet1", Account.class, "accounts.xls", response);
    16. List userList=new ArrayList<>();
    17. User user1=new User(1,"a","12");
    18. User user2=new User(1,"b","12");
    19. User user3=new User(1,"c","12");
    20. userList.add(user1);
    21. userList.add(user2);
    22. userList.add(user3);
    23. //导出操作
    24. byte[] exportUserExcelBytes = ExcelUtil.getExportExcelBytes(userList,"用户信息","sheet1",User.class,"users.xls",response);
    25. fileBufMap.put("accounts.xls",exportAccountExcelBytes);
    26. fileBufMap.put("users.xls",exportUserExcelBytes);
    27. response.setHeader("content-type", "application/octet-stream");
    28. response.setContentType("application/octet-stream");
    29. response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=configDetail.zip");
    30. ZipUtils.downloadZipForByteMore(response.getOutputStream(), fileBufMap);
    31. }

    代码简析:

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

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

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

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

     实现效果:

    好吧,该篇就到这。

  • 相关阅读:
    mysql数据库安装
    ArrayList集合中元素的排序
    CS创世 SD NAND与SPI NAND的对比
    学习前端第二十五天(构造器和操作符‘new’,可选链‘?.’,symbol类型)
    手撕Vuex-实现mutations方法
    Mysql orchestrator高可用
    高维统计理论 Gauss与Rademacher复杂度
    [汇总] Docker容器详解 Macvlan 创建不同容器独立跑仿真(持续更新中)
    机器人抓取检测技术的研究现状
    Vue事件修饰符的使用
  • 原文地址:https://blog.csdn.net/qq_35387940/article/details/125790362