Apache POI XWPF 不替换而是拼接

Apache POI XWPF does not replace but concatenates

我是 Apache POI 新手,在替换文本时遇到问题。

我在这里复制了我的代码Replacing a text in Apache POI XWPF not working

它可以工作,但它不会替换文本,而是将其连接起来。 因此,如果我有 "Quick brown fox jumps over" 并将 "over" 替换为 "under"。我得到 "Quick brown fox jumps overQuick brown fox jumps under".

怎么了?

代码如下:

public class testPOI {

    public static void main(String[] args) throws Exception{

        String filepath = "F:\MASTER_DOC.docx";
        String outpath = "F:\Test.docx";

        XWPFDocument doc = new XWPFDocument(new FileInputStream(filepath));
        for (XWPFParagraph p : doc.getParagraphs()){

            int numberOfRuns = p.getRuns().size();

            // Collate text of all runs
            StringBuilder sb = new StringBuilder();
            for (XWPFRun r : p.getRuns()){
                int pos = r.getTextPosition();
                if(r.getText(pos) != null) {
                    sb.append(r.getText(pos));
                }
            }

            // Continue if there is text and contains "test"
            if(sb.length() > 0 && sb.toString().contains("test")) {
                // Remove all existing runs
                for(int i = 0; i < numberOfRuns; i++) {
                    p.removeRun(i);
                }
                String text = sb.toString().replace("test", "DOG");
                // Add new run with updated text
                XWPFRun run = p.createRun();
                run.setText(text);
                p.addRun(run);
            }
        }
       doc.write(new FileOutputStream(outpath));
    }
}

编辑 1:这很奇怪!我尝试在 2nd 运行 上更换效果很好。第一个 运行 有问题。谁能指出来?

我试过了。有效。

    public class testPOI {

public static void main(String[] args) throws Exception{

    String filepath = "F:\MASTER_DOC.docx";
    String outpath = "F:\Test.docx";

    XWPFDocument doc = new XWPFDocument(new FileInputStream(filepath));
    for (XWPFParagraph p : doc.getParagraphs()){

        int numberOfRuns = p.getRuns().size();

        // Collate text of all runs
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()){
            int pos = r.getTextPosition();
            if(r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }

        // Continue if there is text and contains "test"
        if(sb.length() > 0 && sb.toString().contains("test")) {
            // Remove all existing runs
            for(int i = numberOfRuns; i >=0 ; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("test", "DOG");
            // Add new run with updated text
            XWPFRun run = p.createRun();
            run.setText(text);
            p.addRun(run);
        }
    }
   doc.write(new FileOutputStream(outpath));
}
}