Search code examples
ms-wordvelocityxdocreport

Dynamic number of columns in a Word table using Velocity and XDocReport


XDocReport and Velocity can be used to create a dynamic number of rows in a Word table, using the foreach loop. (The before-row and after-row tokens make this even more powerful.) But the number of columns must be fixed.

But sometimes I don't know the number of columns I will need until the data is added to the template. Is there any way to dynamically set the number of columns? If this was HTML, I could likely easily do this (just by looping through the number of columns and adding another TD or TH element to each row), but I can't figure out how to do this in Word.


Solution

  • You can find a sample with dynamic column in DocxTableWithoutFieldsMetadataWithVelocity.docx in the docxandvelocity-xxx-sample.zip that you can download or in git.

    The basic idea is to use @before-cell/@after-cell :

    enter image description here

    Manage loop for column with HTML and docx is the same thing. You could unzip your docx, edit word/document.xml and add at hand the Velocity code to manage loop for column.

    But it's not very user friendly, that's why XDocReport preprocess the docx to update word/document.xml with Velocity code by using @before-cell/@after-cell written in a mergefield.