把map里面的值替换word里面的${}并输出

wordUtil

 public static void changeText(XWPFDocument document, Map<String, Object> textMap) {
        //获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            //判断此段落时候需要进行替换
            String text = paragraph.getText();
            if (StringUtil.isNotBlank(text) && text.contains("${")) {
                List<XWPFRun> runs = paragraph.getRuns();
                changeValue(runs,textMap);
            }
        }
    }

    public static void changeTable(XWPFDocument document, Map<String, Object> textMap) {
        //获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            //只处理行数大于等于2的表格,且不循环表头
            XWPFTable table = tables.get(i);
            if (table.getRows().size() > 1) {
                //判断表格内容是否可以替换
                String cellText = table.getText();
                if (StringUtil.isNotBlank(cellText) && cellText.contains("${")){
                    List<XWPFTableRow> rows = table.getRows();
                    //遍历表格,并替换模板
                    for (XWPFTableRow row : rows) {
                        List<XWPFTableCell> cells = row.getTableCells();
                        for (XWPFTableCell cell : cells) {
                            //判断单元格内容是否可以替换
                            String cellText1 = cell.getText();
                            if (StringUtil.isNotBlank(cellText1) && cellText1.contains("${")) {
                                //得到单元格的段落
                                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                                for (XWPFParagraph paragraph:paragraphs) {
                                    //遍历段落获得每个段落的行内容
                                    List<XWPFRun> runs = paragraph.getRuns();

                                    changeValue(runs,textMap);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public static void changeValue(List<XWPFRun> runs,Map<String, Object> textMap) {
        for(XWPFRun run : runs) {//遍历行内相同类型的字符
            String valueOfrun = String.valueOf(run);
            int runIndex = runs.indexOf(run);//获得当前run1的坐标
            if (!"".equals(valueOfrun)) {
                if ( valueOfrun.contains("${")||
                     ( valueOfrun.endsWith("$") &&
                       (runIndex + 1) < runs.size() &&
                       String.valueOf(runs.get(runIndex + 1)).startsWith("{")) ) {
                    String appendValueOfRun = valueOfrun;
                    String keys = "";
                    int index = -1;
                    //获取“}”的坐标
                    if (appendValueOfRun.indexOf("${") < appendValueOfRun.indexOf("}")) {
                        index = runIndex;
                    } else {
                        for (int j = runIndex + 1; j < runs.size(); j++) {
                            appendValueOfRun += String.valueOf(runs.get(j));
                            if (String.valueOf(runs.get(j)).contains("}")) {
                                index = j;//获取“}”的坐标
                                break;
                            }
                        }
                    }
                    if (index != -1) {
                        //取${}之间的值
                        keys = appendValueOfRun.substring(appendValueOfRun.indexOf("${") + 2, appendValueOfRun.indexOf("}"));
                        //赋值
                        for (Map.Entry<String, Object> textSet : textMap.entrySet()) {//遍历map的key,相等即进行值的替换
                            if (keys.equals(textSet.getKey())) {
                                String template = "${" + keys + "}";
                                String replace = appendValueOfRun.replace(template, String.valueOf(textSet.getValue()));
                                run.setText(replace, 0);
                                for (int j = runIndex + 1; j <= index; j++) {
                                    runs.get(j).setText("", 0);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

输出

public static void replaceModel(Map map, String sourceFilePath, String targetFilePath)  {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(sourceFilePath);
            XWPFDocument doc = new XWPFDocument(inputStream);
            File file = new File(targetFilePath).getParentFile();
            if (!file.exists()){
                file.mkdirs();
            }
            outputStream = new FileOutputStream(targetFilePath);

            changeText(doc,map);
            changeTable(doc,map);

            doc.write(outputStream);

        } catch (Exception e) {
            logger.error("模板替换异常" + e);
        }
        finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException ignored) {
                    logger.error("关闭流异常" + ignored);
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                    logger.error("关闭流异常" + ignored);
                }
            }
        }
    }

把word转为pdf

 public static void doc2Pdf(String docPath, String pdfPath){
        if (!ExportUtil.GetDocLicense()) {
            logger.error("无法获取Doc License,请联系管理员检查");
        }
        File file = new File(docPath);
        if (file.exists()) {
            BufferedInputStream bufferedInputStream = null;
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                bufferedInputStream = new BufferedInputStream(fileInputStream);
                Document document = new Document(bufferedInputStream);
                document.save(pdfPath, SaveFormat.PDF);
            } catch (Exception e) {
                logger.error("word文件转换为pdf文件异常" + e);
            } finally {
                if (bufferedInputStream != null) {
                    try {
                        bufferedInputStream.close();
                    } catch (IOException ignored) {
                        logger.error("关闭流异常" + ignored);
                    }
                }
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException ignored) {
                        logger.error("关闭流异常" + ignored);
                    }
                }
            }
        }
    }

依赖

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

        <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.14</version>
        </dependency>

doc转pdf和pdf转png用到的依赖

  <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.13</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.13</version>
        </dependency>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值