Search code examples
javascriptexceloffice365office-jsoffice365api

Microsoft office.js Excel add-in - retrieve worksheet/workbook unique ID using javascript/react


We have built an Excel Task pane add in that primarily works with worksheets. As per our requirement we wants to identify excel with there unique ID's whenever user close's the excel and reopen it again.

Sample code to load excel ID from workbook:

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

We are receiving the following error:

Uncaught RichApi.Error: The property 'id' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.


Solution

  • The .sync() method is async and returns a promise that needs to be awaited.

    Therefore, the sync() API call in Office.js returns a promise First Paragraph

    Solution using promises:

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

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