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() { })
    },
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值