Creating Word docx documents dynamically from Grails (or Java :-)

I’m presently working on a little side project that needs to generate a bunch of customisable client reports. One format of interest to our target market is the ubiquitous Word document. Now I know that Word switched to an zipped XML format a while back, so it’s given me a chance to do some researching into what Java libraries might exist for creating and editing the Word xml format.

I’ve played with Apache POI before, but it’s Word support for the latest gear is a little scratchy, so I figured I would hunt around for an nice libraries that people have built for handling the new XML format natively. I didn’t have to hunt far to discover the conveniently named docx4j.

This library gives you everything you need to create/load/edit/write Word docx documents from Java, and comes with a Maven repo, online Javadoc, and nice set of Sample code. What more could you ask for? :-)

But I’m sure you’re just keen to see how to use it in your Grails app, right? Enough talk… First you’ll need to add a couple of entries to your /grails-app/conf/BuildConfig.groovy to make sure you pull in the dependencies. In the extract below, I’ve added a couple of new repos, and the dependency to pull in the docx4j jars:

    repositories {

        // uncomment the below to enable remote dependency resolution
        // from public Maven repositories

        // Details from docx4j Getting Started Guide at
        mavenRepo ""
        mavenRepo ""
    dependencies {
        compile 'org.docx4j:docx4j:2.5.0'

With all our dependencies in place, we’ll just need to create some controller action that generates our Word document and sends it back to the client. I’m going to show one that queries my Asset class to pull back a set of assets and dump them in a Word doc:

  import org.docx4j.openpackaging.packages.WordprocessingMLPackage

  def exportWord = {
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage()
    def mainPart = wordMLPackage.getMainDocumentPart()

    // create some styled heading...
    mainPart.addStyledParagraphOfText("Title", "Asset Library")
    mainPart.addStyledParagraphOfText("Subtitle", "Generated at " + Calendar.getInstance().getTime().toString())

    // Add our list of assets to the document
    Asset.list().each { asset ->

    // write out our word doc to disk
    File file = File.createTempFile("wordexport-", ".docx") file

    // and send it all back to the browser
    response.setHeader("Content-disposition", "attachment; filename=assets.docx");
    response.outputStream << file.readBytes()


With our document sent, the user can fire it up from their browser window. Here's a sample of the output from above:

There are tons of things you can do with customising the documents in memory. I'll be doing some work importing Word templates, customising their fields, then exporting the finished product to the browser. Fun times ahead!

Enjoy your docx generating!

10 thoughts on “Creating Word docx documents dynamically from Grails (or Java :-)

  1. Hi Donal, I think the styles are just the built in Word styles.

    They are not part of the Java library itself – Word just renders the named styled text in whatever that style is set to in Word.

  2. @Donal, @Glen Smith


    The styles are the built-in styles available in MS Word, but you can define your own styles too. “Normal” is the default and apart from “Title” and “Subtitle”, you can also find “Heading 1”, “Heading 2”, … for headings.

  3. Cheers Glen, I too need to make the change from doc to docx, this library looks sweet. I’ve only used POI for .xls and with a few wrappers is nice enough but his looks great!

  4. Hi Glen,
    I have one query. I have a String in java for ex String str = “Tested by achauhan” ; This is a html value . I want to write this value into doc file using java. but i am not getting any to do this.
    I am trying docx4j api with jsoup but i did not get any result yet. Do you have any idea about this. I have searched a lot about it but did not get any thing useful. Please share you knowledge if you can help me with this. :)

    Thanks & Regards

  5. i may suppose to install docx4j to display MS word in eclipse. because each time i try to sysout a imported MS word file in eclipse it crushes. help!

  6. Thank you very much, I will tried ASAP;

    By the way, the library doesn’t exist with Grails 2.3.5.
    The easiest solution I tought:
    1. Go to docx4j, download the jar
    2. Clean your project
    3. Copy the jar in the projectFolder->lib
    4. Right-click on the project and choose Groovy Tools -> Refresh Dependencies

  7. Hoho, now is working :) Thank you very much (again!)

    For newbies like me in Grails, remember to add the doc mime type support:


    grails.mime.types = [
    docx: ‘application/vnd.openxmlformats-officedocument.wordprocessingml.document’

Comments are closed.