How to Generate Dynamic Word Documents in Java Using Templates (Apache POI)
Generating Word documents dynamically using templates in Java is a common requirement in enterprise applications. Whether you need to create reports, invoices, or contracts, leveraging templates allows for consistency and efficiency. In this post, we’ll explore how to generate Word documents dynamically using Apache POI, a powerful Java library for handling Microsoft Office documents.
Why Use Templates for Word Document Generation?
- Customization: Dynamically populate data into placeholders.
- Consistency: Ensures uniform document structure.
- Efficiency: Reduces repetitive manual work.
Prerequisites
Before you begin, make sure you have the following dependencies in your Maven project:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
Steps to Generate Word Documents Using Templates
1. Create a Word Template (.docx)
Prepare a Word document with placeholders like {name}
, {date}
, {amount}
to be replaced dynamically.
2. Load the Template in Java
Use Apache POI to read the template and replace placeholders with dynamic values.
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class WordTemplateProcessor {
public static void main(String[] args) throws Exception {
String templatePath = "template.docx";
String outputPath = "generated_document.docx";
Map<String, String> replacements = new HashMap<>();
replacements.put("{name}", "John Doe");
replacements.put("{date}", "2025-02-27");
replacements.put("{amount}", "$1000");
processTemplate(templatePath, outputPath, replacements);
System.out.println("Document generated successfully!");
}
public static void processTemplate(String templatePath, String outputPath, Map<String, String> replacements) throws Exception {
FileInputStream fis = new FileInputStream(new File(templatePath));
XWPFDocument document = new XWPFDocument(fis);
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null) {
for (Map.Entry<String, String> entry : replacements.entrySet()) {
text = text.replace(entry.getKey(), entry.getValue());
}
run.setText(text, 0);
}
}
}
FileOutputStream fos = new FileOutputStream(new File(outputPath));
document.write(fos);
fos.close();
document.close();
}
}
3. Run the Code and Generate Documents
Execute the Java program, and it will generate a new Word document with replaced values.
Conclusion
Using Apache POI, we can efficiently generate Word documents dynamically based on predefined templates. This approach is useful for creating reports, invoices, and contracts without manually formatting documents every time.
Post Comment