批量生成Excel,打包成zip后下载

Updated on with 0 views and 0 comments

根据上传的Excel,拿到不同的sheet解析后打包为zip下载

@PostMapping("/upload")
    @ResponseBody
    public String uploadFile(MultipartFile file, HttpServletResponse response) throws IOException {
        Map<String, XSSFWorkbook> map = parseJLLService.ParseJLLExcel(file);
        String originalFilename = file.getOriginalFilename();
        originalFilename = originalFilename.substring(0,originalFilename.lastIndexOf("."))+".zip";
        //初始化返回
        Set<String> fileNames = map.keySet();
//        ZipInputStream zipInputStream= null;
        response.reset();
        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/msexcel");
        response.setContentType("application/x-zip-compressed");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(originalFilename.getBytes("utf-8"), "ISO-8859-1"));
        response.addHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Content-Disposition", "attachment; filename=" + testName);
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
        for (String fileName : fileNames) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            XSSFWorkbook xssfWorkbook = map.get(fileName);
            xssfWorkbook.write(byteArrayOutputStream);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            ZipEntry zipEntry = new ZipEntry(fileName+".xlsx");
            zipOutputStream.putNextEntry(zipEntry);
            zipOutputStream.write(bytes);
            xssfWorkbook.close();
            byteArrayOutputStream.close();
        }
        zipOutputStream.flush();
        zipOutputStream.close();
        return "success";
    }