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

如何使用Office JS在Windows版Office 2016中实现Excel单元格添加批注功能

问题原因

  • API版本不兼容:Windows版Office 2016(永久许可版)默认仅支持Excel JavaScript API 1.1,而你代码中使用的workbook.comments系列操作是Excel API 1.10 版本才新增的能力。Mac版Office、Office 365均支持更高版本的API集,因此可以正常运行,Office 2016永久版无该API能力所以无法插入批注。
  • 代码逻辑不严谨:你调用wb.comments.getItemByCell(address)后未执行ctx.sync()加载对象就直接调用delete方法,在部分严格校验的环境下会直接抛出对象未加载的异常。

解决方案

方案1:兼容Windows Office 2016(使用旧版备注API)

Office 2016仅支持旧版的单元格备注功能(对应现在Office中的「备注」,和新版线程批注属于不同能力),可以使用Range.note属性实现,兼容所有版本:

await Excel.run(async (ctx) => {
  const address = "sheet!A4";
  const range = ctx.workbook.worksheets.getItem("sheet").getRange("A4");
  range.note = "This is simple test comment";
  await ctx.sync();
  console.log("Add note successfully!");
});

方案2:仅面向高版本Office使用新版批注API

如果不需要兼容Office 2016,可以优化原有代码的逻辑,规避加载错误:

await Excel.run(async (ctx) => {
  const wb = ctx.workbook;
  const address = "sheet!A4";
  // 先尝试加载目标单元格的批注
  const comment = wb.comments.getItemByCell(address);
  comment.load("id");
  await ctx.sync()
    .then(() => {
      // 批注存在则删除
      comment.delete();
    })
    .catch((error) => {
      if (error.code !== Excel.ErrorCodes.itemNotFound) {
        throw error;
      }
    });
  // 新增批注
  wb.comments.add(address, "This is simple test comment");
  await ctx.sync();
  console.log("Add comment successfully!");
});

如果要在Windows环境使用新版批注API,需要用户升级到Office 2019及以上版本,或者切换为Office 365订阅版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:06:04