
- Apache POI Word - Home
- Apache POI Word - Overview
- Apache POI Word - Installation
- Apache POI Word - Core Classes
- Apache POI Word - Document
- Apache POI Word - Paragraph
- Apache POI Word - Borders
- Apache POI Word - Tables
- Apache POI Word - Font & Alignment
- Apache POI Word - Text Extraction
- Apache POI Word Resources
- Apache POI Word - Quick Guide
- Apache POI Word - Useful Resources
- Apache POI Word - Discussion
Apache POI Word - Tables
In this chapter, you will learn how to create a table of data in a document. You can create a table data by using XWPFTable class. By adding each Row to table and adding each cell to Row, you will get table data.
Create a Table
First of all, let us create a Table using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a Document first, and then we can create a table.
The following code snippet is used to create and populate a table −
//Create Blank document XWPFDocument document = new XWPFDocument(); //create table XWPFTable table = document.createTable(); //create first row XWPFTableRow tableRowOne = table.getRow(0); //set data in column one tableRowOne.getCell(0).setText("col one, row one");
Example - Create Table in a Document
The following code is used to creating table in a document −
ApachePoiDocDemo.java
package com.tutorialspoint; import java.io.File; import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; public class ApachePoiDocDemo { public static void main(String[] args)throws Exception { //Blank Document XWPFDocument document = new XWPFDocument(); //Write the Document in file system FileOutputStream out = new FileOutputStream(new File("example.docx")); //create table XWPFTable table = document.createTable(); //create first row XWPFTableRow tableRowOne = table.getRow(0); tableRowOne.getCell(0).setText("col one, row one"); tableRowOne.addNewTableCell().setText("col two, row one"); tableRowOne.addNewTableCell().setText("col three, row one"); //create second row XWPFTableRow tableRowTwo = table.createRow(); tableRowTwo.getCell(0).setText("col one, row two"); tableRowTwo.getCell(1).setText("col two, row two"); tableRowTwo.getCell(2).setText("col three, row two"); //create third row XWPFTableRow tableRowThree = table.createRow(); tableRowThree.getCell(0).setText("col one, row three"); tableRowThree.getCell(1).setText("col two, row three"); tableRowThree.getCell(2).setText("col three, row three"); document.write(out); out.close(); document.close(); System.out.println("example.docx written successully"); } }
Output
It generates a Word file named example.docx in your current directory and display the following output on the command prompt −
example.docx written successfully
The example.docx file looks as follows −

Advertisements