What I have implemented is a find replace feature(from here);
In my template docx file I am using "id like texts", __heading1__, __subjectname__, Then replacing with them using code below. For tables @axel-richters solution may be suitable.
private void findReplace(String a, String b, CustomXWPFDocument document){
for (XWPFParagraph p : document.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains(a)) {
text = text.replace(a, b);
r.setText(text, 0);
}
}
}
}
}