Add Table to Word Example
This program demonstrates adding tables into a Word file.
Problem Statement
Write a Java program that creates a table in a Word .docx file.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.poi.xwpf.usermodel.*; |
| 3 | public class WordTableExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq Word Table Example"); |
| 6 | XWPFDocument doc=new XWPFDocument(); |
| 7 | XWPFTable table=doc.createTable(); |
| 8 | XWPFTableRow row1=table.getRow(0); |
| 9 | row1.getCell(0).setText("ID"); |
| 10 | row1.addNewTableCell().setText("Name"); |
| 11 | row1.addNewTableCell().setText("Country"); |
| 12 | XWPFTableRow row2=table.createRow(); |
| 13 | row2.getCell(0).setText("1"); |
| 14 | row2.getCell(1).setText("Arun"); |
| 15 | row2.getCell(2).setText("India"); |
| 16 | try(FileOutputStream fos=new FileOutputStream("table.docx")) { |
| 17 | doc.write(fos); |
| 18 | System.out.println("Eduinq Table Added Successfully"); |
| 19 | } catch(IOException e) { |
| 20 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 21 | } |
| 22 | } |
| 23 | } |
Program Output
Eduinq Word Table Example Eduinq Table Added Successfully
Explanation
Tables created using createTable(). - Rows and cells populated with text. - Exception handling ensures safe operations. - In enterprise systems, tables are used for structured reports. Conclusion: Shows adding tables to Word files.