Search code examples
office-jsscriptlab

How can I get a list of worksheets in an Excel workbook and display them in the add-in UI?


I'm trying to do some work in an Office JS Add-in.

I've looked at both the Script Lab and side-loading via yeoman.

I just haven't been able to find enough example code to get over the hump of learning how to work with React / Typescript on top of learning the Office and Excel API itself.

It would be really great if someone could demonstrate a simple extension of the Script Lab "List worksheets" example to put the list of sheets into the Taskpanel (add-on UI) instead of simply dumping them into console.log().

Also, one follow-up question: My goal is to port some code from a Google Sheets App Script so we can do the same thing in Excel. The project is specific to just one workbook and is not going to be distributed. Is it better to do this in the real Office Add-In context and suffer side-loading it (will we really always have to run a separate node server!?) or to try to do it all in Script Lab? I like the ease of the Script Lab route, but I worry because it has warning plastered all over it that it is for experimentation and prototyping rather than production work.


Solution

  • At its core, an Office (web) Add-in is simply a web app -- i.e., the task pane is your canvas (UI) that contains various HTML elements, and you can update/manipulate the contents of the task pane by using JavaScript/TypeScript. Therefore, you can write output to the task pane by simply specifying the HTML element(s) that will contain the output, and then using JavaScript/TypeScript to set the value of the element(s).

    For example, you could specify a span element within the HTML:

    <span id="result"></span>
    

    And then populate this element via the script as follows:

    $('#result').html('This is the result!');
    

    I've created a snippet that illustrates this approach for the List Worksheets operation. You can try the snippet yourself by using Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following Gist URL: https://gist.github.com/kbrandl/a4a1e4da51385707863aec0ebdf296f6.

    Finally, comments regarding your follow-up question:

    • Script Lab is an experimental tool that you can use to learn about developing Office Add-ins; it is not an official Microsoft product, it is not supported, and it is not intended for use in production use cases.
    • To use an add-in in a production use case, it's recommended that you deploy the add-in (web app) to a web server and then use any of the available methods for publishing the add-in.