Let’s start with the very first line of the code:
Excel.run. Because the sample code is based in an Excel scenario, I will use the term
Excel.run for the remainder of this chapter – but the concept is 100% equivalent to
Excel.run is a function that, in turn, accepts a function as its input parameter. This inner function – typically referred to as the batch function – describes the work that we’d like Excel to do. When you look at the population-data sample from the previous section, almost the entire code – other than the
Excel.run line at the beginning, and the
.catch(...) block at the very end – is part of this batch function.
The batch function accepts a request context parameter, which is the means by which the communication with the host happens. In the population-data sample, you saw the context used in two ways:
- Use the
contextto fetch the
documentin Word, etc.), and do the other object-navigation from there. A couple examples:
var table = context.workbook.tables.getItem("PopulationTable");
var outputSheet = context.workbook.worksheets.add(
"Top 10 Growing Cities");
- Use the
contextas part of a
context.sync()– which will be covered shortly in a subsequent section, but, at a high-level, is essential in order to “commit” any local changes back into the document.
You can think of the
Excel.run as a boiler-plate preamble; it is the batch function that is the star of the show, but it needs a request context in order to start off the chain of OM calls. The
Excel.run call is simply a means to that end, as it creates a new request context that it passes into the batch function. Because nothing can happen without a request context, you will see that essentially all code in this book and in the documentation begin with this
Word.run, etc.) incantation.
Thus, the typical and simplest use-case for the
run method is simply:
Note that because
Excel.run returns a Promise object, it should always be followed by a
.catch(...) – either directly following it, as in the code above, or somewhere downstream.
For purposes of getting started, that is really all that you need to know about
Excel.run. With this
Excel.run preamble out of the way, the subsequent sections will focus on what you can do within the batch function, after the process has been jump-started by the