import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
//http://stackoverflow.com/questions/22268898/replacing-a-text-in-apache-poi-xwpf
public class XWPFUtils {
public static void replaceFromArray(String []arrFrom, String[] arrTo, String fnameIN, String fnameOUT) {
XWPFDocument doc=null;
try {
doc = new XWPFDocument(OPCPackage.open(fnameIN));
} catch (InvalidFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
paragraphReplace(arrFrom,arrTo,r);
}
}
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p1 : cell.getParagraphs()) {
for (XWPFRun r : p1.getRuns()) {
paragraphReplace(arrFrom,arrTo,r);
}
}
}
}
}
}
try {
doc.write(new FileOutputStream(fnameOUT));
System.out.println("Done");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
/* if (pkg!=null)
try {
pkg.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/ }
}
private static void paragraphReplace( String[] arrFrom, String[] arrTo, XWPFRun r) {
String text = r.getText(0);
if (text != null) {
for(int i=0; i<arrFrom.length;i++) {
if (text.contains(arrFrom[i])) {
text = text.replace(arrFrom[i], arrTo[i]);
System.out.println("Replacement:"+arrFrom[i]+"|"+arrTo[i]);
r.setText(text, 0);
}
}
}
}
}