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

如何使用NPOI在XWPFTableCell的两个段落之间插入表格?

NPOI 实现Word表格单元格内指定位置插入新表格
  • 核心逻辑是定位单元格内元素的插入索引,原有第一个段落索引为0,插入到索引1的位置即可落在两个段落之间
  • 插入完成后可直接对新生成的内嵌表格进行内容填充和样式配置

代码示例:

using NPOI.XWPF.UserModel;
using System.IO;

// 读取模板文件
using FileStream fs = new FileStream("模板.docx", FileMode.Open, FileAccess.Read);
XWPFDocument doc = new XWPFDocument(fs);

// 定位外层表格和目标单元格,索引根据实际模板结构调整
XWPFTable outerTable = doc.Tables[0];
XWPFTableCell targetCell = outerTable.GetRow(0).GetCell(0);

// 校验单元格内段落数量满足要求
if (targetCell.Paragraphs.Count >= 2)
{
    // 插入位置:第一个段落之后,第二个段落之前
    int insertIndex = 1;
    // 插入2行2列的内嵌表格,行列数可自定义
    XWPFTable innerTable = targetCell.InsertNewTable(insertIndex, 2, 2);

    // 填充内嵌表格内容
    innerTable.GetRow(0).GetCell(0).SetText("序号");
    innerTable.GetRow(0).GetCell(1).SetText("名称");
    innerTable.GetRow(1).GetCell(0).SetText("1");
    innerTable.GetRow(1).GetCell(1).SetText("测试数据");
}

// 保存生成的文件
using FileStream outFs = new FileStream("输出.docx", FileMode.Create, FileAccess.Write);
doc.Write(outFs);

若插入表格后原有段落出现多余空行,可调用targetCell.RemoveParagraph(insertIndex + 1, false)删除多余的自动生成段落,第二个参数传false避免误删原有内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:45:03