1
votes

I'm using Apache POI with Jython to create tables and place them in certain positions of a docx where I have bookmarks. I can find the bookmarks (CTBookmark objects) by their names, create a cursor in the beginning of the paragraph where they are placed and then create a new table there with:

cursor = para.getCTP().newCursor() #para is the paragraph where the bookmark is placed
table = document.insertNewTbl(cursor) #cursor is an XMLCursor

If I would just insert text I could use:

nextNode = bookmark.getDomNode() #considering it is the node named 'bookmarkEnd'
run = para.createRun()
run.setText('foo')
para.getCTP().getDomNode().insertBefore(run.getCTR().getDomNode(),nextNode)

But to insert another element, like a table, I can't find a solution. It would be better if the table was placed inside the bookmark, but if it would be placed just before it, instead of in the beginning of the paragraph, it would be great too.

I appreciate any help or alternative idea. Thanks.

1

1 Answers

0
votes

Almost there, you need to create the rows and the cells.

A example to register.

I hope helping.

XWPFTable table = doc.insertNewTbl(cursor);
for(int rowIndex=0; rowIndex < 3; rowIndex++){
    String line = "LineContent "+rowIndex;
    XWPFTableRow row = table.getRow(rowIndex);

    if(row==null){
        row = table.createRow();       
    }

    for(int colIndex=0; colIndex < 2; colIndex++){
        XWPFTableCell  cell = row.getCell(colIndex);
        if(cell == null){
          cell = row.createCell();
        }

        cell.setText(line+" Col "+colIndex);
     }

}