How to feed Word 2010 (.docx) documents/templates with data from MySQL database?

Mirko picture Mirko · Sep 5, 2012 · Viewed 10.2k times · Source

What would be the best approach to replace placeholders in a .docx document (Word 2010) with data coming from a MySQL database?

Can I just open the file using a server side language and do a string replace per each placeholder?

Is there any existing tool/library available?

Thanks

Answer

JasonPlutext picture JasonPlutext · Sep 6, 2012

**Disclosure: I lead the docx4j project **

There are heaps of existing tools/libraries available!

Yes, you can just do a string replace, but that is a brittle approach, since Word may have split the string across runs.

You can use MERGEFIELDs, or content control data binding.

docx4j supports all three approaches, but content control data binding is the most powerful.

One thing to consider especially is "repeats". If you want say a row of a table in Word, for each matching row in your MySQL table, then you need a way to make this happen.

docx4j does this with a "repeat" content control around the table row; whichever solution you choose, I'd make sure up front that it can handle repeats.