Guillaume Piquet
Guillaume Piquet

Reputation: 1

JAVA POI DOCX replace text in paragraph

Hi i m trying to replace some text in a docx file, but i got problemes with text to be replaced that can be on multiple runs. So i tried this : but it erase everything in the document :/

private void replaceText(XWPFParagraph p, String target, String replacement) {
    if (p.getRuns() != null) {
        String paragraph = p.getText();
        for (int i = 0; i < p.getRuns().size(); i++) {
            p.removeRun(i);
        }
        paragraph = paragraph.replace(target, replacement);
        XWPFRun r = new XWPFRun(CTR.Factory.newInstance(), p);
        r.setText(paragraph, 0);

    }
}

Upvotes: 0

Views: 3932

Answers (2)

centic
centic

Reputation: 15872

For one of my projects I chose a different route, I work on the underlying XML data and do a search/replace there which usually works quite nicely.

See https://github.com/centic9/poi-mail-merge for the details, but basically I fetch the CTBody low-level item via

CTBody body = doc.getDocument().getBody();

And then read the full XML body text

// read the current full Body text
String srcString = body.xmlText();

then do the replacements.

Finally I create a new CTBody item with the new contents via

CTBody makeBody = CTBody.Factory.parse(resultStr);

See https://github.com/centic9/poi-mail-merge/blob/master/src/main/java/org/dstadler/poi/mailmerge/MailMerge.java#L81 for the full code-details as there are a few more things that are handled to make it work nicely.

Upvotes: 2

Rahul
Rahul

Reputation: 380

It will surely erase everything because you are removing all the runs in the paragraph. Point to understand here is that the text in the paragraph is stored inside the runs. What getText() does is it returns all the text in all the runs of the paragraph.
Removing all runs and adding just one new run will surely disrupt the font and alignment of the text

You are removing all the runs and then adding one run with the replaced text. I believe this is not what you wish to achieve.

Just loop over the runs and replace the text inside them. 

Upvotes: 2

Related Questions