Add Table to Word Doc using POI

In many cases we need to deal with tables in the Word Document. Apache POI makes it simple to add table to the Word Document. Lets see the way to add table to word doc using POI.

Classes / Interfaces Used


org.apache.poi.xwpf.usermodel.XWPFTable is used to create simple table.


org.apache.poi.xwpf.usermodel.XWPFTableRow is used to create a Row of the table


org.apache.poi.xwpf.usermodel.XWPFTableCell is used to create a cell of the table

The Code

Creating table is very simple. You already have the document object created from the XWPFDocument. Using that we can create simple table

Now creating the 1st Row and 1st Cell is different from creating the rest of Rows and Cells.
Creating First Row
XWPFTableRow tableRow0 = table.getRow(0);

Creating First Cell of First Row
XWPFTableCell tableCell0 = tableRow0.getCell(0);

Creating Next Cell to the First Row
XWPFTableCell tableCell1 = tableRow0.addNewTableCell();

Creating Next Rows and Next Cells
XWPFTableRow tableRow1 = table.createRow();
tableRow1.getCell(0).setText(” Row 1 Column 0 “);

You will see comments in the code below for better understanding of the Row and Cell creation process


Add Table to Word Doc using POI