Create docx file from a template file in java

Spencer Bharath picture Spencer Bharath · Aug 26, 2016 · Viewed 7k times · Source

I need to create docx files based on a templates. The template should contain the place holders and I should be able to fill the the place holders from java . Is it possible to do it , If so suggest me the good and efficient way to do it .

Answer

Tom picture Tom · Oct 3, 2017

A little late for the original question, but if anyone else needs to dynamically create docx documents from templates, you might want to have a look at the DocxStamper Java library which I created on top of docx4j.

It allows to use the Spring Expression Language in docx templates and you can create a document out of a template with a couple lines like this:

MyData data = ...;           // your own POJO containing the data      
InputStream template = ...;  // InputStream to the template file
OutputStream out = ...;      // OutputStream to the resulting document
DocxStamper stamper = new DocxStamperConfiguration()
    .build();
stamper.stamp(template, context, out);
out.close();