【问题标题】:Microsoft office.js Excel add-in - retrieve worksheet/workbook unique ID using javascript/reactMicrosoft office.js Excel 加载项 - 使用 javascript/react 检索工作表/工作簿唯一 ID
【发布时间】:2020-01-29 13:28:10
【问题描述】:

我们已经构建了一个 Excel 任务窗格插件,主要用于工作表。根据我们的要求,每当用户关闭 excel 并重新打开它时,我们希望使用唯一 ID 识别 excel。

从工作簿加载 excel ID 的示例代码:

Office.initialize = () => {
  Excel.run(function(context) {
    var sheet = context.workbook.worksheets.getItem("Sheet1");
    const worksheets = context.workbook.worksheets;
    //tried to load ID property using below code
    worksheets.load("id, name");
    worksheets.load(["items/id", "items/name"]);
    worksheets.load(["id", "name", "worksheet/id"]);
    sheet.load(["items/id", "items/name"]);
    context.sync();
    //below is the code to print excel ID
    console.log(sheet.id);
    // OR
    worksheets.items.forEach(ws => {
      console.log(`id: ${ws.id}, name: ${ws.name}`)
    });
  }).catch(function(error) {
    console.log(error.debugInfo);
  });
}

我们收到以下错误:

未捕获的 RichApi.Error:属性“id”不可用。在读取属性值之前,调用包含对象的 load 方法,并在关联的请求上下文中调用“context.sync()”。

【问题讨论】:

  • 您尝试过:sheet.load('id');sheet.load({ id: true}); 吗? Link to doc
  • 尝试使用 sheet.load('id')
  • 我发布了一个包含解决方案的答案 :)
  • 感谢 Lumpenstein。它真的很有帮助。

标签: javascript excel office365 office-js office365api


【解决方案1】:

.sync() 方法是异步的,并返回一个需要等待的承诺。

因此,Office.js 中的 sync() API 调用返回一个承诺 First Paragraph

使用承诺的解决方案:

  Office.initialize = () => {
    Excel.run(function (context) {
      var sheet = context.workbook.worksheets.getItem("Sheet1");
      sheet.load(["items/id", "items/name"]);
      context.sync().then(() => {
        console.log(sheet.id);
      });
    });
  }).catch(function(error) {
    console.log(error.debugInfo);
  });
}

使用 async/await 的解决方案:

  Office.initialize = () => {
    Excel.run(async function (context) {
      var sheet = context.workbook.worksheets.getItem("Sheet1");
      sheet.load(["items/id", "items/name"]);
      await context.sync()
      console.log(sheet.id);
    });
  }).catch(function(error) {
    console.log(error.debugInfo);
  });
}

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多