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

如何使用Office JS在Word表格中添加新行并为单元格赋值?

为Word表格新插入的行赋值

你可以通过以下方式为新插入的行的单元格赋值:

  1. 调用insertRows时保存返回的新行对象,该方法会返回插入的行集合
  2. 加载新行的cells属性,确保能访问到对应单元格
  3. 同步上下文后,直接操作单元格的内容

修改后的完整代码如下:

await Word.run(async (context) => {
    const selection = context.document.getSelection();
    selection.load('parentTableCellOrNullObject');
    await context.sync();

    if (!selection.isNull && !selection.parentTableCellOrNullObject.isNull) {
        const parentCell = selection.parentTableCellOrNullObject;
        const parentRow = parentCell.parentRow;

        // 插入新行并保存引用
        const newRow = parentRow.insertRows(Word.InsertLocation.after, 1).getFirst();
        // 加载新行的cells属性
        newRow.load('cells');
        await context.sync();

        // 为单元格赋值,示例:按索引设置不同单元格的文本
        newRow.cells.getItemAt(0).body.setText("新行第一列内容");
        newRow.cells.getItemAt(1).body.setText("新行第二列内容");
        
        await context.sync();
        console.log('新行已添加并完成单元格赋值');
    } else {
        console.log('当前选择位置不在表格单元格内');
    }
});

补充说明:

  • 若需要沿用原行的内容,可以先加载原行的cells属性,同步后获取原单元格内容再赋值给新行
  • 单元格索引从0开始,可通过cells.getItemAt(index)精准定位目标单元格
  • 除了setText,还可以使用body.insertText()等方法插入富文本内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:01:03