Java – Updating the text of a XWPFParagraph using Apache POI

apache-poijava

I have been able to loop through all paragraphs in a document and get at the text and everything and I have read and understood how you can create a document from scratch. But how can I update and replace the text in a paragraph? I can do createRun in a paragraph but that will just create a new piece of text in it.

 ...
 FileInputStream fis = new FileInputStream("Muu.docx");
 XWPFDocument myDoc = new XWPFDocument(fis);
 XWPFParagraph[] myParas = myDoc.getParagraphs();
 ...

My theory is that I need to get at the existing "run" in the paragraph I want to change, or delete the paragraph and add it again) but I cannot find methods to do that.

Best Answer

You can't change the text on a XWPFParagraph directly. A XWPFParagraph is made up of one or more XWPFRun instances. These provide the way to set the text.

To change the text, your code would want to be something like:

public void changeText(XWPFParagraph p, String newText) {
   List<XWPFRun> runs = p.getRuns();
   for(int i = runs.size() - 1; i > 0; i--) {
      p.removeRun(i);
   }
   XWPFRun run = runs.get(0);
   run.setText(newText, 0);
}

That will ensure you only have one text run (the first one), and will replace all the text to be what you provided.