Dependencies
First, download the dependency files as mentioned in the Introduction to Apache POI For Manipulation of MS Office Documents with Java tutorial. After downloading the libraries, you have to add them to JAVA_PATH. Alternatively, you can create an Eclipse project and add them to the project as a library. You are being suggested to add the libraries as an internal library instead of an external library.If you are not familiar with library linking, follow these steps.
Create a directory, lib, in your project. Put the jars in the lib directory. Right-click on the project, select Properties, go to Java Build Path, click on Add Jars and browse the lib directory you have created. It's done!
Explanation of Source Code
Create an instance of FileOutputStream for the Demo.docx file.Create an instance of XWPFDocument class for .docx file.
Create an instance of XWPFTable class to create a table.
Create an instance of XWPFTableRow class to create a row.
Prepare the content of the table and finally write the content.
Try the following code.
package com.bunks.demo.poi;
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 WordDocumentTableDemo {
public static void main(String[] args) {
XWPFDocument xwpfDocument = new XWPFDocument();
try (FileOutputStream fileOutputStream = new FileOutputStream(new File("Demo.docx"))) {
XWPFTable xwpfTable = xwpfDocument.createTable();
XWPFTableRow xwpfTableRow = xwpfTable.getRow(0);
xwpfTableRow.getCell(0).setText("Sl.");
xwpfTableRow.addNewTableCell().setText("Name");
xwpfTableRow.addNewTableCell().setText("Address");
xwpfTableRow = xwpfTable.createRow();
xwpfTableRow.getCell(0).setText("1.");
xwpfTableRow.getCell(1).setText("Jogn");
xwpfTableRow.getCell(2).setText("john@abc.com");
xwpfTableRow = xwpfTable.createRow();
xwpfTableRow.getCell(0).setText("2.");
xwpfTableRow.getCell(1).setText("Rich");
xwpfTableRow.getCell(2).setText("rich@xyz.com");
xwpfDocument.write(fileOutputStream);
xwpfDocument.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.