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

2023-12-20 05:34:54

后台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() { })
    },

文章来源:https://blog.csdn.net/ghx123456ghx/article/details/135091015
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。