java替换word文档中的指定字段,包括段落和表格中有段落的情况

说明:遇到的需求中,表格内还有段落,看了网上很多博客都是分享的表格中只有单元格的情况,踩了很多坑,总算调试出来了。话不多说,流程走起来。

//获取项目路径

String property = System.getProperty("user.dir");
String srcPath = property + "/src/main/resources/static/template/xxx.docx";

//新建map存参数

Map<String, String> contentMap = new HashMap();
 map.put("${m1a}","1");

//调用方法
//第三个参数为指定的输出文件

 getBuild(srcPath,map,"D:/test.docx");

//关键方法

public static void getBuild(String  srcPath, Map<String, String> contentMap, String exportFile) {
     
        try {
     
            XWPFDocument document = new XWPFDocument(new FileInputStream(srcPath));

            // 替换段落中的指定文字
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
     
                XWPFParagraph paragraph = itPara.next();
                commonCode(paragraph,contentMap);
            }

            // 替换表格中的指定文字
            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
     
                XWPFTable table = itTable.next();
                int rcount = table.getNumberOfRows();
                for (int i = 0; i < rcount; i++) {
     
                    XWPFTableRow row = table.getRow(i);
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
     
                        //单元格中有段落,得做段落处理
                        List<XWPFParagraph> paragraphs = cell.getParagraphs();
                        for (XWPFParagraph paragraph : paragraphs) {
     
                            commonCode(paragraph,contentMap);
                        }
                    }
                }
            }
            FileOutputStream outStream = new FileOutputStream(exportFile);
            document.write(outStream);
            outStream.close();
        }catch (Exception e){
     
            e.printStackTrace();
        }
    }

    private static void commonCode(XWPFParagraph paragraph,Map<String, String> contentMap){
     
        List<XWPFRun> runs = paragraph.getRuns();
        for (XWPFRun run : runs) {
     
            String oneparaString = run.getText(run.getTextPosition());
            if (StringUtils.isBlank(oneparaString) || !oneparaString.contains("$")){
     
                continue;
            }
            for (Map.Entry<String, String> entry :
                    contentMap.entrySet()) {
     
                oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
            }
            run.setText(oneparaString, 0);
        }
    }

//关于word文档
要替换的${},最好粘贴在记事本里去掉格式,否则可能会替换失败。

你可能感兴趣的:(java,poi)