Page 1 of 1

docx4j Modify Table

PostPosted: Fri Aug 04, 2017 7:25 am
by prakhar211
Hi,

I have table in the word document and using docx4j api i would need to dynamically add more columns to this table and want to populate values for these newly added columns/rows.
Could you please help me with the sample code for doing this?

Re: docx4j Modify Table

PostPosted: Fri Aug 04, 2017 11:07 am
by jason
Given a table Tbl tbl, you can access its content with tbl.getContent() which returns List<Object>. In the simple case, these are table row objects (Tr), but other stuff is also possible. For example, a table row can be wrapped in a content control.

To add a "column", you need to add a table cell to each Tr object. (You do that by adding a tc to the Tr object's content list). See TblFactory for an example.

You should also add a new gridCol entry, as shown in that code.

Re: docx4j Modify Table

PostPosted: Wed Aug 09, 2017 3:01 am
by prakhar211
Thanks for the reply. I made some changes but still it is not adding the proper way

So i have one table in the word document and i want to modify the table by adding more columns to the header and rows.

Please refer attachement, first three elements on the left coming from the word document and element [3] is added by below code. As you can see the content is blank for 3rd but it shows [SelectionAppAnswer] is the content for [2] on the left.

Tr templateRow = (Tr) rows.get(1);
Tc tc = Context.getWmlObjectFactory().createTc();
P p = Context.getWmlObjectFactory().createP();
p.getContent().add("someText");
tc.getContent().add(p);
JAXBElement element = new javax.xml.bind.JAXBElement(new QName(""), Tc.class, tc);
element.setValue(tc);
templateRow.getContent().add(element);

Please suggest how to do it.

Re: docx4j Modify Table

PostPosted: Wed Aug 09, 2017 9:35 am
by jason
Two problems:

1. You should also add a new gridCol entry
2. javax.xml.bind.JAXBElement(new QName(""), Tc.class, tc) looks wrong. Instead, just templateRow.getContent().add(tc)

Re: docx4j Modify Table

PostPosted: Fri Aug 11, 2017 5:46 am
by prakhar211
I was able to add and populate dynamic columns using below JAXBElement

javax.xml.bind.JAXBElement(new QName(""), Tc.class, tc)

As shown in the screenshot the word template rowdata comes as JAXBElement so that's why i have to use like above statement to avoid exceptions. Otherwise when earlier i tried using templateRow.getContent().add(tc), i think it was throwing error.

Can i continue using javax.xml.bind.JAXBElement(new QName(""), Tc.class, tc) or it seems completely incorrect to you?