读取word模板.替换word模板中的内容

/**
 * 模板下载
 * 1.先获取模板,读取模板中的段落信息;
 * 2.解析段落信息,看究竟查询哪一个流程的信息(通过流程名称去380中查询id后再去500中查询具体数据)
 * 3.替换模板中段落里面的标签信息,例如$(A),替换为1;
 * 4.导出替换后的模板;
 *
 * @param dto
 * @return
 * @throws BLException
 * @throws UnsupportedEncodingException
 */
public IGOCRG01DTO downloadAttachmentAction(IGOCRG01DTO dto) throws BLException, IOException {
    log.info(">>模板下载操作开始...");
    //1.接受参数
    IGOCRG0101Form igocrg0101Form = dto.getForm();
    String attrKey = igocrg0101Form.getAttachmentKey();
    String date_start = igocrg0101Form.getOcrgDate_Start();
    String date_end = igocrg0101Form.getOcrgDate_End();
    //2.读取模板key,name
    AttachmentSearchCondImpl attachmentSearchCond = new AttachmentSearchCondImpl();
    attachmentSearchCond.setAttkey(attrKey);
    List<Attachment> attachmentList = attachmentBL.searchAttachmentList(attachmentSearchCond);
    Attachment attachment = attachmentList.get(0);
    //读取指定附件
    String rootPath = "";
    rootPath += ResourceUtility.getString("UPLOAD_FILE_ROOT_PATH_OCRG");
    StringBuffer filepath = new StringBuffer(rootPath);
    filepath.append(attrKey);
    filepath.append("/");
    filepath.append(attachment.getAttname());
    //3.读取对照表 $(A):事件/服务请求管理
    HashMap<String, String> hmReplacePara = new HashMap<>();
    HashMap<String, String> hmOCRGValueToOCRGKey = new HashMap<>();
    HashMap<String, String> hmPdIdToPdName = new HashMap<>();
    ArrayList<String> alProcessName = new ArrayList<>();
    List<OcrgContrastInfo> ocrgContrastInfoList = ocrgContrastBL.searchOcrgContrast();
    for (int i = 0; i < ocrgContrastInfoList.size(); i++) {
        OcrgContrastInfo ocrgContrastInfo = ocrgContrastInfoList.get(i);
        String ocrgkey = ocrgContrastInfo.getOcrgkey();
        String ocrgvalue = ocrgContrastInfo.getOcrgvalue();
        hmOCRGValueToOCRGKey.put(ocrgvalue, ocrgkey);
        hmReplacePara.put(ocrgkey, "0");
    }
    if (filepath.toString().toLowerCase().endsWith("docx")) {
        //读取模板文件
        XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(filepath.toString()));
        //获取文档中的段落;
        List<XWPFParagraph> xwpfParagraphList = document.getParagraphs();
        for (int i = 0; i < xwpfParagraphList.size(); i++) {
            XWPFParagraph xwpfParagraph = xwpfParagraphList.get(i);
            String paraGraphStr = xwpfParagraph.getText();
            if (StringUtils.isNotEmpty(paraGraphStr)) {
                for (Map.Entry<String, String> entry : hmOCRGValueToOCRGKey.entrySet()) {
                    String ocrgValue = entry.getValue();
                    if (paraGraphStr.contains(ocrgValue)) {
                        alProcessName.add(entry.getKey());
                    }
                }
                log.debug("文档中的段落信息: " + xwpfParagraph.getText());
            }
        }
        //读取IG380
        ArrayList<String> alPdId = new ArrayList<>();
        for (int i = 0; i < alProcessName.size(); i++) {
            //读取ig380
            IG380SearchCondImpl ig380SearchCond = new IG380SearchCondImpl();
            ig380SearchCond.setPdname(alProcessName.get(i));
            List<IG380Info> ig380InfoList = ig380BL.searchIG380Info(ig380SearchCond);
            if (ig380InfoList != null) {
                for (int j = 0; j < ig380InfoList.size(); j++) {
                    IG380Info ig380Info = ig380InfoList.get(j);
                    alPdId.add(ig380Info.getPdid());
                    hmPdIdToPdName.put(ig380Info.getPdid(), ig380Info.getPdname());
                }
            }
        }
        //查询IG500,按照流程关闭时间查询
        IG500SearchCondImpl ig500SearchCond = new IG500SearchCondImpl();
        String[] pdIdArr = new String[alPdId.size()];
        alPdId.toArray(pdIdArr);
        ig500SearchCond.setPrpdid_like_or(pdIdArr);
        ig500SearchCond.setPropentime_from(date_start + " 00:00");
        ig500SearchCond.setPropentime_to(date_end + " 23:59");
        List<IG500Info> ig500InfoList = ig500BL.searchIG500Info(ig500SearchCond);
        for (int i = 0; i < ig500InfoList.size(); i++) {
            IG500Info ig500Info = ig500InfoList.get(i);
            String pdId = ig500Info.getPrpdid();
            String pdName = hmPdIdToPdName.get(pdId);
            if (hmOCRGValueToOCRGKey.containsKey(pdName)) {
                String ocrgKey = hmOCRGValueToOCRGKey.get(pdName);
                if (hmReplacePara.containsKey(ocrgKey)) {
                    String num = hmReplacePara.get(ocrgKey);
                    hmReplacePara.put(ocrgKey, String.valueOf(Integer.parseInt(num) + 1));
                }
            }
        }
        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) {
            //段落信息
            XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
            List<XWPFRun> runs = paragraph.getRuns();
            for (int i = 0; i < runs.size(); i++) {
                //段落中文字
                String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());
                for (Map.Entry<String, String> entry : hmReplacePara.entrySet()) {
                    //替换段落中文字
                    if (oneparaString.contains(entry.getKey())) {
                        log.debug("普通文字--docx--替换前:" + oneparaString);
                        oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
                    }
                }
                //重新set给段落
                runs.get(i).setText(oneparaString, 0);
                log.debug("普通文字----docx-替换后:" + oneparaString);
            }
            String exceptionCondition = runs.toString();
            log.debug("段落分不清特殊处理,去掉逗号空格啥的生成风险报告--普通文字----docx-替换前:" + exceptionCondition);
            //破API段落分不清特殊处理,去掉逗号空格啥的
            if (StringUtils.isNotEmpty(exceptionCondition)) {

                exceptionCondition = exceptionCondition.replace(",", "").replace(" ", "");
                if (exceptionCondition.length() > 2)
                    exceptionCondition = exceptionCondition.substring(1, exceptionCondition.length() - 1);
                if (exceptionCondition.contains("##<") && exceptionCondition.contains(">##")) {
                    for (Map.Entry<String, String> entry : hmReplacePara.entrySet()) {
                        exceptionCondition = exceptionCondition.replace(entry.getKey(), entry.getValue());
                    }
                    runs.get(0).setText(exceptionCondition, 0);
                    log.info("段落分不清特殊处理,去掉逗号空格啥的生成风险报告--普通文字----docx-替换后:" + exceptionCondition);
                    for (int i = 1; i < runs.size(); i++) {
                        runs.get(i).setText("", 0);
                    }
                }
            }
        }
        HttpServletResponse response = dto.getResponse();
        response.reset();
        response.setContentType("binary/octet-stream");
        OutputStream output = null;
        try {
            String docTitle = "一键式报告生成数据.docx";
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(docTitle.getBytes("gb2312"), "iso-8859-1"));
            output = response.getOutputStream();
            //执行导出
            document.write(output);
        } catch (Exception e) {
            log.error("接口定义信息-导出Word异常");
            e.printStackTrace();
        } finally {
            try {
                // 关闭输出流
                if (output != null) {
                    output.flush();
                    output.close();
                }
                if (output != null) {
                    output.flush();
                    output.close();
                }
            } catch (Exception e) {
                log.error(">>导出Word关闭输出流异常:" + e.getMessage());
            }
        }
    }
    log.info(">>模板下载操作结束...");
    return dto;
}

猜你喜欢

转载自blog.csdn.net/qq_34004756/article/details/91490413