পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Sunday, January 15, 2017

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 Table

The following code is used to creating table in a document:
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 CreateTable {
   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("create_table.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();
      System.out.println("create_table.docx written successully");
   }
}
Save the above code in a file named CreateTable.java. Compile and execute it from the command prompt as follows:
$javac CreateTable.java
$java CreateTable
It generates a Word file named createtable.docx in your current directory and display the following output on the command prompt:
createtable.docx written successfully
The createtable.docx file looks as follows:
Create Table

No comments:

Post a Comment