java生成多个excel并生成zip

java生成多个excel并生成zip

框架:若依框架

思路:

1.生成不同excel的workBook对象

2.循环把excel文件写到zip流中

 @GetMapping("/export/file")
    public void exportFile(HttpServletResponse resp, @RequestParam String requestNo) throws Exception{
       service.exportFile(resp, requestNo);
    }

// 生成workBook对象这块改了改若依框架中的excel导出

ExcelUtil<FileDetail> util = new ExcelUtil<FileDetail>(FileDetail.class);
        Workbook workbook = util.exportExcelToZip(resp, csf, "xxxxx");
 private void zipFile(HttpServletResponse resp, List<WorkBook> workbooks,String requestNo) throws IOException {
       
        ServletOutputStream out = resp.getOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(out);
        try {
        resp.setContentType("application/octet-stream; charset=UTF-8");
        resp.setHeader("Content-Disposition", "attachment; filename=" + requestNo + ".zip");
               for (Workbook workbook : workbooks) {
                ZipEntry z = new ZipEntry("abc.xlsx");
                zipOutputStream.putNextEntry(z);
                workbook.write(zipOutputStream);
            }

            zipOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //注意关闭顺序,否则可能文件错误
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
            if (out != null) {
                out.close();
            }
        }

    }

你可能感兴趣的:(java基础,java,开发语言)