Replacing a text in Apache POI XWPF not working

后端 未结 5 1812
Happy的楠姐
Happy的楠姐 2020-12-11 09:20

I\'m currently trying to work on the code mentioned on a previous post called Replacing a text in Apache POI XWPF.

I have tried the below and it works but I don\'t k

5条回答
  •  一整个雨季
    2020-12-11 10:04

    just change text for every run in your paragraph, and then save the file. this code worked for mi

    XWPFDocument doc = new XWPFDocument(new FileInputStream(filepath));
    for (XWPFParagraph p : doc.getParagraphs()) {
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
        String text = r.getText(0);
        if (text != null && text.contains("variable1")) {
            text = text.replace("variable1", "valeur1");
            r.setText(text, 0);
        }
        if (text != null && text.contains("variable2")) {
            text = text.replace("variable2", "valeur2");
            r.setText(text, 0);
        }
        if (text != null && text.contains("variable3")) {
            text = text.replace("variable3", "valeur3");
            r.setText(text, 0);
        }
        }
    
    }
    
    doc.write(new FileOutputStream(outpath));
    

提交回复
热议问题