Programmatic Word Document Generation with Apache POI
Add the following dependencies to your Maven configuration:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
The following implementation demonstrates creating a structured Word template:
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class DocumentGenerator {
public void exportToFile(String outputPath) {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph titlePara = doc.createParagraph();
titlePara.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = titlePara.createRun();
titleRun.setText("Report Template");
titleRun.setBold(true);
titleRun.setFontSize(18);
XWPFParagraph contentPara = doc.createParagraph();
XWPFRun contentRun = contentPara.createRun();
contentRun.setText("Dynamic content section");
try (FileOutputStream out = new FileOutputStream(outputPath)) {
doc.write(out);
} catch (IOException e) {
throw new RuntimeException("Document generation error", e);
} finally {
try {
doc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new DocumentGenerator().exportToFile("output.docx");
}
}
To variable substitution within exitsing templates, read the source file before processing:
import java.io.FileInputStream;
public void populateTemplate(String templatePath, String targetPath, String replacement) {
try (XWPFDocument template = new XWPFDocument(new FileInputStream(templatePath));
FileOutputStream out = new FileOutputStream(targetPath)) {
for (XWPFParagraph paragraph : template.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null && text.contains("{{placeholder}}")) {
run.setText(text.replace("{{placeholder}}", replacement), 0);
}
}
}
template.write(out);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}