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

使用office.js API无法读取现有Word文档中Content Controls的问题

问题原因

Office.js 基于代理对象模式实现与 Office 客户端的交互,文档侧的属性/集合默认不会自动同步到加载项的本地运行环境。你直接访问context.document.contentControls.items.length时,没有提前加载contentControls集合的属性,也没有执行同步操作,所以永远拿不到有效数值。

修正方案

你需要在读取属性前先调用load方法指定要获取的内容,执行context.sync()完成数据同步后再读取对应值,修正后的countControls函数示例如下:

export async function countControls() {
  console.log("In Count Controls");
  return Word.run(async (context) => {
    // 第一步:加载contentControls集合的items属性
    context.document.contentControls.load("items");
    // 第二步:执行同步,把文档侧的内容控件数据拉到本地
    await context.sync();
    // 现在才能正常读取长度
    let numberOfControls = context.document.contentControls.items.length;
    const para = context.document.body.insertParagraph(
      "Number of controls: " + numberOfControls,
      Word.InsertLocation.end
    );
    para.font.color = "blue";
    await context.sync();
  }).catch((error) => {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

getByTag()方法的正确使用示例

如果要按标签筛选内容控件,同样需要遵循「加载-同步-读取」的逻辑,示例如下:

// 按标签获取内容控件示例
async function getControlsByTag(tagName) {
  await Word.run(async (context) => {
    const matchedControls = context.document.contentControls.getByTag(tagName);
    // 加载匹配到的集合的items属性
    matchedControls.load("items");
    await context.sync();
    // 现在可以正常遍历匹配到的内容控件
    console.log(`匹配到${matchedControls.items.length}个标签为${tagName}的内容控件`);
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:48:02