Search code examples
docx4j

DocX4: How to add table in word docx using Quick part field and write to that template with a table


I would like to add table in my docx template. I know how to do it with just a simple field and how to use that template and write the value to it. But how can I create a table and write to the template. Assuming I have a list of Students object, how am I going to write it in a table?

This is how you add field name.

Quick Parts > Fields > Choose MergeField in the category and write the desired field name

And here's how to write the value to it using docx4j

Map<DataFieldName, String> map = new HashMap<DataFieldName, String>();
map.put(new DataFieldName("myName"),"yourName");
                MailMerger.setMERGEFIELDInOutput(MailMerger.OutputField.DEFAULT);

MailMerger.performMerge(template, map, true);

template.save(new File("C:/temp/OUT_SIMPLE.docx") );

Solution

  • Assuming you want one row per list item, the easiest way is to iterate through the list, writing your table rows.

    To generate suitable code, create a Word document with the table looking as you want it, then generate corresponding code.

    Alternatively, you could use OpenDoPE content control data binding, wrapping a repeat around a table row. This is a more generic solution, but with a learning curve...