I can replace the text inside the table and footer, but I can't replace the text outside the table. I don't know why.
Please any idea how to replace a paragraph like ${name}
outside the table ?
I want that in the Map.
public static boolean changWord(String inputUrl, String outputUrl, Map<String, String> textMap) {
// Template conversion default success
boolean changeFlag = true;
try {
File file = new File(outputUrl);
FileOutputStream stream = new FileOutputStream(file);
@SuppressWarnings("resource")
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
WorderToNewWordUtils.changeText(document, textMap);
document.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
changeFlag = false;
}
return changeFlag;
}
public static void changeText(XWPFDocument document, Map<String, String> textMap) {
for (XWPFParagraph p : document.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (checkText(text)) {
r.setText(changeValue(r.toString(), textMap), 0);
}
}
}
// Replace Text inside Table
for (XWPFTable tbl : document.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 (checkText(text)) {
r.setText(changeValue(r.toString(), textMap), 0);
}
// System.out.println("Bevor Fußzeiler" + text);
}
}
}
}
}
// Replace Text in Footer
for (XWPFFooter footer : document.getFooterList()) {
for (XWPFParagraph paragraph1 : footer.getParagraphs()) {
for (XWPFRun r : paragraph1.getRuns()) {
String text = r.getText(0);
if (checkText(text)) {
r.setText(changeValue(r.toString(), textMap), 0);
}
// System.out.println("Nach Fußzeile" + text);
}
}
}
}
public static boolean checkText(String text) {
boolean check = false;
if (text.indexOf("$") != -1) {
check = true;
}
return check;
}
public static String changeValue(String value, Map<String, String> textMap) {
for (Map.Entry<String, String> textSet : textMap.entrySet()) {
// match template and replacement value format ${key}
String key = "${" + textSet.getKey() + "}";
if (value.indexOf(key) != -1) {
value = textSet.getValue();
}
}
return value;
}
public static void main(String[] args) {
// Template file address
String inputUrl = "D:\\Test.docx";
Map<String, String> testMap = new HashMap<>();
testMap.put("ja", "Nein");
testMap.put("red", "Blue");
testMap.put("No", "yes");
testMap.put("Preis", "999$");
testMap.put("Something", "Nothing");
testMap.put("nein", "Ja");
testMap.put("antwort", "Schöne");
testMap.put("name", "Sayer");
testMap.put("Test", "Email");
// .pdf if you want the Document in PDF Format
String outputUrl = "D:\\New-Test.docx";
WorderToNewWordUtils.changWord(inputUrl, outputUrl, testMap);
}
}