springboot导出excel和文件压缩包

代码解析:

  1. ZipOutputStream:导出zip的输出流
  2. ZipEntry:压缩包中的文件
  3. zos.putNextEntry():向压缩包中添加文件

导出代码

/**
     * 导出zip
     * @param excelFileName excel文件名
     * @param zipFileName   zip文件名
     * @param workbook  excel的工作簿
     * @param fileList  附件
     * @param response
     */
    private void exportZip(String excelFileName, String zipFileName, Workbook workbook, List<File> fileList,HttpServletResponse response){
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + new String(zipFileName.getBytes("GB2312"), "ISO8859-1"));
            response.setCharacterEncoding("UTF-8");
            // 直接导出到ZipOutputStream即可
            ZipOutputStream zos = new ZipOutputStream(outputStream, Charset.forName("GBK"));
            byte[] buf = new byte[1024];
            for (File file : fileList) {
                FileInputStream inputStream = new FileInputStream(file);
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                int len;
                while ((len = inputStream.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                inputStream.close();
            }
            zos.putNextEntry(new ZipEntry(excelFileName));
            workbook.write(zos);
            zos.closeEntry();
            if (zos != null) {
                zos.flush();
                zos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new JeroBootException("导出失败");
        }
    }

你可能感兴趣的:(spring,boot,java,后端)