You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Apache POI实现Word表格的单元格内嵌套表格?

在Word表格单元格中嵌套表格(Apache POI实现)

可以实现Word表格单元格嵌套表格的功能,以下是对现有代码的修改方案:

修改后的完整代码

public class PoiTest3 {

    public static void main(String[] args) throws Exception {

        try (XWPFDocument doc = new XWPFDocument()) {

            // 创建外层表格
            XWPFTable outerTable = doc.createTable();

            // 第一行
            XWPFTableRow row1 = outerTable.getRow(0);
            row1.getCell(0).setText("First Row, First Column");
            row1.addNewTableCell().setText("First Row, Second Column");
            row1.addNewTableCell().setText("First Row, Third Column");

            // 第二行
            XWPFTableRow row2 = outerTable.createRow();
            row2.getCell(0).setText("Second Row, First Column");
            // 在第二行第二列单元格中嵌套表格
            XWPFTableCell nestedCell = row2.getCell(1);
            // 清空单元格原有空段落,避免干扰嵌套表格显示
            nestedCell.removeParagraph(0);
            // 创建嵌套表格
            XWPFTable nestedTable = nestedCell.addNewTbl();
            // 设置嵌套表格第一行
            XWPFTableRow nestedRow1 = nestedTable.createRow();
            nestedRow1.getCell(0).setText("嵌套表格行1列1");
            nestedRow1.addNewTableCell().setText("嵌套表格行1列2");
            // 设置嵌套表格第二行
            XWPFTableRow nestedRow2 = nestedTable.createRow();
            nestedRow2.getCell(0).setText("嵌套表格行2列1");
            nestedRow2.getCell(1).setText("嵌套表格行2列2");
            // 外层表格第二行第三列
            row2.getCell(2).setText("Second Row, Third Column");

            // 第三行
            XWPFTableRow row3 = outerTable.createRow();
            row3.getCell(0).setText("Third Row, First Column");
            row3.getCell(1).setText("Third Row, Second Column");
            row3.getCell(2).setText("Third Row, Third Column");

            // 保存文档
            try (FileOutputStream out = new FileOutputStream("c:\\excel\\table.docx")) {
                doc.write(out);
            }

        }

    }
}

关键操作说明

  • 选中目标单元格:确定需要嵌入表格的外层单元格(示例中为第二行第二列)
  • 清除默认段落:单元格默认自带空段落,必须移除否则会导致嵌套表格排版异常
  • 创建嵌套表格:通过单元格的addNewTbl()方法生成内部表格,后续可像操作普通表格一样设置行、列及内容

示例效果

示例效果图片

内容的提问来源于stack exchange,提问作者keep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:05:38