Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a text in Apache POI XWPF

I just found Apache POI library very useful for editing Word files using Java. Specifically, I want to edit a DOCX file using Apache POI's XWPF classes. I found no proper method / documentation following which I could do this. Can somebody please explain in steps, how to replace some text in a DOCX file.

** The text may be in a line / paragraph or in a table row/column

Thanks in Advance :)

like image 419
Gagan93 Avatar asked Mar 08 '14 11:03

Gagan93


People also ask

What is XWPFRun?

XWPFRun object defines a region of text with a common set of properties.


1 Answers

The method you need is XWPFRun.setText(String). Simply work your way through the file until you find the XWPFRun of interest, work out what you want the new text to be, and replace it. (A run is a sequence of text with the same formatting)

You should be able to do something like:

XWPFDocument doc = new XWPFDocument(OPCPackage.open("input.docx")); for (XWPFParagraph p : doc.getParagraphs()) {     List<XWPFRun> runs = p.getRuns();     if (runs != null) {         for (XWPFRun r : runs) {             String text = r.getText(0);             if (text != null && text.contains("needle")) {                 text = text.replace("needle", "haystack");                 r.setText(text, 0);             }         }     } } for (XWPFTable tbl : doc.getTables()) {    for (XWPFTableRow row : tbl.getRows()) {       for (XWPFTableCell cell : row.getTableCells()) {          for (XWPFParagraph p : cell.getParagraphs()) {             for (XWPFRun r : p.getRuns()) {               String text = r.getText(0);               if (text != null && text.contains("needle")) {                 text = text.replace("needle", "haystack");                 r.setText(text,0);               }             }          }       }    } } doc.write(new FileOutputStream("output.docx")); 
like image 133
Gagravarr Avatar answered Sep 20 '22 10:09

Gagravarr