Microsoft office.js Excel 加载项 - 使用 javascript/react 检索工作表/工作



我们构建了一个主要处理工作表的 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(("。

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

因此,Office.js 中的 sync(( API 调用返回一个承诺 第一段

使用承诺的解决方案:

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);
});
}

最新更新