Microsoft Word

Aus bestehenden Word-Dokument Text ändern:

public class FundB_ParserZahlenBU {
	public static void main(String[] args) {

try {	
	XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream("C:\\Users\\...docx")));
	for (XWPFParagraph p : doc.getParagraphs()) {
	    StringBuilder sb = new StringBuilder();
	    for (XWPFRun r : p.getRuns()) {
	    String text = r.getText(0);
	    if (text != null && text.contains("string1")) {
	        text = text.replace("string1", "kunde1");
	        r.setText(text, 0);
	    }
	    if (text != null && text.contains("string2")) {
	        text = text.replace("string2", "kunde2");
	        r.setText(text, 0);
	    }
	    if (text != null && text.contains("string3")) {
	        text = text.replace("string3", "kunde3");
	        r.setText(text, 0);
	    }
	    }

	}

	doc.write(new FileOutputStream("C:\\Users\\...docx"));
        } catch (Exception ex) {
	ex.printStackTrace();
}
}

Aus bestehenden Word-Dokument Wert in einer Tabelle (Zelle) ändern:

public class FundB_ParserZahlenBU {
	public static void main(String[] args) {

		try {
			XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream("C:\\Users\\...docx")));
			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("sollErsetztWerden")) {
				                text = text.replace("sollErsetztWerden", "neuerWert");
				                r.setText(text,0);
				              }
				            }
				         }
				      }
				   }
				}
			doc.write(new FileOutputStream("C:\\Users\\...docx"));
			doc.close();
			} catch (Exception ex) {
			ex.printStackTrace();
			}

}