How to Use the XWPFTable Class in Java to Format Word File Tables
You can use the XWPFTable class in the Apache POI library to format Word file tables. The following Maven dependencies need to be added:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
The following is an example Word file:
text
┌─────────────┬───────────┬───────────┐
| Column 1 | Column 2 | Column 3 |
├─────────────┼───────────┼───────────┤
Line 1 | Line 1 | Line 1 | Line 1 |
├─────────────┼───────────┼───────────┤
Line 2 | Line 2 | Line 2 | Line 2 |
├─────────────┼───────────┼───────────┤
| Line 3 | Line 3 | Line 3 | Line 3 |
└─────────────┴───────────┴───────────┘
The following is the Java sample code:
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WordTableFormattingExample {
public static void main(String[] args) {
//Create a new Word document
XWPFDocument document = new XWPFDocument();
//Create Table
XWPFTable table = document.createTable(4, 3);
//Set Table Style
table.getCTTbl().getTblPr().unsetTblBorders();
//Set header content
XWPFTableRow headerRow = table.getRow(0);
HeaderRow. getCell (0). setText ("Column 1");
HeaderRow. getCell (1). setText ("Column 2");
HeaderRow. getCell (2). setText ("Column 3");
//Set Table Content
for (int row = 1; row <= 3; row++) {
XWPFTableRow tableRow = table.getRow(row);
TableRow. getCell (0). setText ("row"+row);
TableRow. getCell (1). setText ("row"+row);
TableRow. getCell (2). setText ("row"+row);
}
//Save Document
try (FileOutputStream out = new FileOutputStream(new File("table_example.docx"))) {
document.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This example code creates a table, sets the header and content, and saves the table to the name 'table'_ Example. docx ` in the Word file. The table style will be set to borderless.