如何使用 Java 向 word 文档添加表格

问题描述

如何使用 Java 向 word 文档添加表格。

解决方案

以下是使用 Java 向 word 文档添加表格的程序。

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 TablesToWord {
   public static void main(String[] args)throws Exception {

        //空白文档
        XWPFDocument document = new XWPFDocument();
        
        //将文档写入文件系统
        FileOutputStream out = new FileOutputStream(new File("create_table.docx"));
        
        //创建表格
        XWPFTable table = document.createTable();
        
        //创建第一行
        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");
        
        //创建第二行
        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");
        
        //创建第三行
        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");
   }
}

输出

添加表格
java_apache_poi_word.html