3
votes

I want to manipulate text runs in the XWPFDocument using Apache POI 3.10 and the method XWPFRun.setText() does not work the way I was expecting. This code:

XWPFDocument doc = new XWPFDocument(resp.getContent());
for (XWPFParagraph paragraph : doc.getParagraphs()) {
    for (XWPFRun run : paragraph.getRuns()) {
        int textPosition = run.getTextPosition();
        if (run.getText(textPosition) != null) {
            System.out.println("old value: " + run.getText(textPosition));
            run.setText("value changed", textPosition);
            System.out.println("new value: " + run.getText(textPosition));
        }
    }
}

produces the output:

old value: change me
new value: change me

What is the correct way of updating single run in XWPFDocument?

2
You don't appear to have any code writing the file out again after the changes - is it that simple?Gagravarr
@Gagravarr Yes, it is that simple... However, I do not understand why it is required to store doc in a file in order to have changes applied.Artur Malinowski
Because that's how the library works - it loads it into memory, you make changes in memory, then you save. Just the same as Word - you need to tell it to save when you're done!Gagravarr
Nope. I make changes in memory using setText(), so I want to read from memory with getText(). For me it is quite obvious while using methods similar to getters and setters. And if you replace text in Word, you can see the replaced value without saving.Artur Malinowski
Ah, I understand now! What happens if you use XWPFRun.toString() to get the text out of the run, does that help? And have you made sure you're using the latest version of Apache POI?Gagravarr

2 Answers

0
votes

I had to use run.toString() to solve an issue similar to yours. (org.apache.poi 3.15) The output from .toString() is changed after setText(..) is called.

System.out.println("toString(): " + run.toString());

0
votes

It's been a while and the explanation is somehow hidden between comments, so it may be worth to sum it up.

Actually, there is no bug in Apache POI behavior. The problem is in the naming convention - although POI uses get/set methods, it does not mean that classes obey JavaBeans rules. In this example, setText method really does the job - all of the changes would be applied after saving edited document.