excel或word模板填充数据后模板导出并压缩为zip导出

后台util

fileParamList中为每个模板的参数,参数包括filePath模板文件路径(templates下面的),downloadFileName为带后缀的文件名

    public static void batchDownLoadExcelForZip(List<Map<String, Object>> fileParamList, HttpServletResponse response)
            throws Exception {
   

        OutputStream os = null;
        ZipOutputStream zipOutputStream = null;
        try{
   

            response.setHeader("Content-disposition", "attachment; filename=" + "test.zip");
            response.setContentType("application/zip; charset=utf-8");
            os = new BufferedOutputStream(response.getOutputStream());

            zipOutputStream = new ZipOutputStream(os);
            for(Map<String, Object> paramMap:fileParamList){
   
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if("word".equals(paramMap.get("fileType"))){
   
                    InputStream is = TemplateExcelUtils.class.getClassLoader().getResourceAsStream("templates/"+paramMap.get("filePath"));
                    if(null!=is){
   
                        XWPFTemplate template = XWPFTemplate.compile(is).render(new HashMap<>());
                        template.write(baos);
                        is.close();
                    }
                }else{
   //导出excel
                    Workbook workBook = getWorkBookForDownLoad(paramMap);
                    //将workbook写入内存流
                    workBook.write(baos);
                    workBook.close();
                }
                ZipEntry zipEntry = new ZipEntry((String) paramMap.get("downloadFileName"));
                zipOutputStream.putNextEntry(zipEntry);
                //将内存流写入zip文件
                zipOutputStream.write(baos.toByteArray());
            }
        }catch (Exception e){
   
            e.printStackTrace();
            throw e;
        }finally {
   
            if(null !=zipOutputStream){
   
                zipOutputStream.closeEntry();
                zipOutputStream.flush();
                zipOutputStream.close();
            }
            if(null != os){
   
                os.close();
            }
        }
    }
    private static Workbook getWorkBookForDownLoad(Map<String, Object> fileParams) throws Exception {
   
        Workbook workbook = null;
        try {
   
            //读取模板
            InputStream is = TemplateExcelUtils.class.getClassLoader().getResourceAsStream("templates/"+fileParams.get("filePath"));
            XLSTransformer transformer = new XLSTransformer();
            //向模板中写入内容
            workbook = transformer.transformXLS(is, fileParams);
            HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);
            if(ObjectUtils.isNotEmpty(fileParams.get("mergCellNos"))){
   
                List<Map<String,Integer>> mergCellNoMaps = (List<Map<String, Integer>>) fileParams.get("mergCellNos");
                for(Map<String,Integer> mergMap:mergCellNoMaps){
   
                    sheet.addMergedRegion(new CellRangeAddress(mergMap.get("firstRow"),mergMap.get("lastRow"),mergMap.get("firstCell"),mergMap.get("lastCell")));//起始行,截止行号,起始列,截止列
                }
            }
        }catch (Exception e){
   
            e.printStackTrace();
            throw e;
        }finally {
   
            if(null !=workbook){
   
                //workbook.close();
            }
        }
        return workbook;
    }

controller

    @PostMapping("/exporttest")
    public void exportDirectorData(@RequestBody Map<String, Object> param, HttpServletResponse httpServletResponse) {
   
        List<Map<String, Object>> fileParamList = cmBaseDirectorExport.getFileParams(param);
        try{
   
            TemplateExcelUtils.batchDownLoadExcelForZip(fileParamList,httpServletResponse);
        }catch (Exception e){
   
            e.printStackTrace();
        }
    }

前台写法

   handleExportDs() {
   
      const that = this
      // const queryParams = JSON.parse(JSON.stringify(this.queryParams))
      let param = {
    id: '123' }
      this.$confirm('请确认是否导出?', '警告', {
   
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
   
          that.loading = true
          request({
   
            method: 'post',
            url: 'test/exporttest',
            data: param,
            responseType: 'blob'
          }).then(res => {
   
            that.loading = false
            const aLink = document.createElement('a')
            var fileName = '测试数据导出' + moment().format('YYYYMMDDHHmmss') + '.zip'
            fileName = fileName.replace(/\"/g, '')
            const url = window.URL.createObjectURL(res)
            aLink.href = url
            aLink.download = fileName
            aLink.click()
            aLink.remove()
            URL.revokeObjectURL(url)
          })
        })
        .catch(function() {
    })
    },

最近更新

  1. TCP协议是安全的吗?

    2023-12-20 11:18:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-20 11:18:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-20 11:18:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-20 11:18:03       18 阅读

热门阅读

  1. rpc和消息队列区别

    2023-12-20 11:18:03       34 阅读
  2. js对象转换为excel,excel转换为js对象

    2023-12-20 11:18:03       41 阅读
  3. MATLAB 平面拟合并旋转到水平面 (43)

    2023-12-20 11:18:03       32 阅读
  4. Https图片链接下载问题

    2023-12-20 11:18:03       45 阅读
  5. Https接口调用问题

    2023-12-20 11:18:03       37 阅读
  6. (c语言)关机程序

    2023-12-20 11:18:03       39 阅读
  7. ubuntu 22.04 安装 lfs

    2023-12-20 11:18:03       38 阅读