美文网首页
根据word模板生成word文件

根据word模板生成word文件

作者: 十九贝勒 | 来源:发表于2022-01-28 13:15 被阅读0次

    公司有个生成合同内容的需求,需要近期完成,于是找了度娘整理了一下。

    引入pom依赖

    <dependency>
              <groupId>org.apache.poi</groupId>
              <artifactId>poi-ooxml</artifactId>
              <version>4.1.2</version>
     </dependency>
    

    首先得准备一下模板文件

    image.png

    读取解析文件

      InputStream in = null;
            try {
                in = new FileInputStream(templatePath);
                //获取docx解析对象
                document = new XWPFDocument(in);           
                document.close();
            }catch (Exception e){
                e.printStackTrace();
            }
    

    解析段落标签

     /**
         * 替换段落文本
         *
         * @param document docx解析对象
         * @param textMap  需要替换的信息集合
         */
        public static void changeText(XWPFDocument document, Map<String, String> textMap) {
            //获取段落集合
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                //获取到段落中的所有文本内容
                String text = paragraph.getText();
             
            }
        }
    

    判断是否需要替换内容

     /**
         * 判断文本中是否包含$
         *
         * @param text 文本
         * @return 包含返回true, 不包含返回false
         */
        public static boolean checkText(String text) {
            boolean check = false;
            if (text.indexOf("$") != -1) {
                check = true;
            }
            return check;
        }
    

    根据map内容替换参数

     /**
         * 匹配传入信息集合与模板
         *
         * @param value   模板需要替换的区域
         * @param textMap 传入信息集合
         * @return 模板需要替换区域信息集合对应值
         */
        public static String changeValue(String value, Map<String, String> textMap) {
            System.out.println("value::"+value+"::");
            String mapKey=value.trim().replace("${","").replace("}","");
            String mapValue=textMap.get(mapKey);
            if(StringUtils.isNotEmpty(mapValue)){
                value ="  "+mapValue+"  ";//value.replace("${"+mapKey+"}",mapValue);
            }
            //模板未匹配到区域替换为空
            if (checkText(value)) {
                value = "";
            }
            return value;
        }
    
    # 替换模板内容
     List<XWPFRun> runs = paragraph.getRuns();
      for (XWPFRun run : runs) {   
           //替换模板原来位置
            run.setText(changeValue(run.toString(), textMap), 0);
      }
    

    保存文件

     File dest = (new File(fileName)).getCanonicalFile();
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                changeText(document, replaceMap);
                document.write(new FileOutputStream(dest));
    

    运行查看效果

    image.png

    源码传送门

    word模板生成文件Util

    相关文章

      网友评论

          本文标题:根据word模板生成word文件

          本文链接:https://www.haomeiwen.com/subject/lzekhrtx.html