Updating XWPFP Paragraph Text Using Apache POI

I managed to look through all the paragraphs in the document and get the text and thatโ€™s all, and I read and understood how you can create a document from scratch. But how can I update and replace text in a paragraph? I can do createRun in the paragraph, but that just creates 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 the existing โ€œstartโ€ in the paragraph that I want to change, or delete the paragraph and add it again), but I can not find methods for this.

+4
source share
1 answer

You cannot directly modify text in XWPFParagraph. An XWPFParagraph consists of one or more instances of XWPFRun. They provide a way to set text.

To change the text, your code will look something like this:

 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); } 

This ensures that you have only one text run (first) and will replace all text with what you provided.

+11
source

Source: https://habr.com/ru/post/1315204/


All Articles