# Office.js API

The xlwings API covers the most common parts of Excel’s object model. For everything else, xlwings Lite gives you access to the full [Office.js Excel API](https://learn.microsoft.com/en-us/javascript/api/excel) from Python with `book.officejs()`. The Office.js API is complex, so you will probably want [Wingman](wingman.md) to write the code for you. Wingman knows the API well and only falls back to it when the xlwings API doesn’t cover a feature.

#### NOTE
Office.js access requires xlwings>=0.37.13 in `requirements.txt`.

## A first example

```python
import xlwings as xw
from xlwings import script


@script
async def highlight_negatives(book: xw.Book):
    sheet = book.sheets["Sales"]
    async with book.officejs() as ctx:
        # Office.js objects of xlwings objects
        sheet.api.tabColor = "#C00000"
        rng = sheet["B2:B20"].api
        cf = rng.conditionalFormats.add("CellValue")
        cf.cellValue.format.fill.color = "#FFC7CE"
        cf.cellValue.rule = {"formula1": "=0", "operator": "LessThan"}

        # Anything else starts from the workbook
        sheets = ctx.workbook.worksheets
        sheets.load("items/name,items/tabColor")
        await ctx.sync()
        for item in sheets.items:
            print(item.name, item.tabColor)
```

The code inside the `async with` block is the Office.js Excel API written in Python syntax: it keeps the camelCase names of Office.js and its string values for enums, such as `"CellValue"` or `"LessThan"`. Office.js samples translate almost line by line: use `ctx` where they use `context`, and drop the `await Excel.run(...)` around them.

## The session

`book.officejs()` returns a session that you use as an asynchronous context manager. In a script, this requires an `async def` function, while notebooks support `async with` at the top level of a cell. The session (`ctx` in the examples) forwards Office.js members to the [`RequestContext`](https://learn.microsoft.com/en-us/javascript/api/excel/excel.requestcontext), so you can use `ctx.workbook`, `ctx.application` or `ctx.load(obj, "values")` as you would use `context` in Office.js. The most important members are:

| Member             | Description                                                                                                                                                                   |
|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ctx.workbook`     | The Office.js [`Workbook`](https://learn.microsoft.com/en-us/javascript/api/excel/excel.workbook), the starting point for everything that xlwings doesn’t have an object for. |
| `ctx.application`  | The Office.js [`Application`](https://learn.microsoft.com/en-us/javascript/api/excel/excel.application), e.g. for `ctx.application.calculate("Full")`.                        |
| `await ctx.sync()` | Runs the recorded Office.js code in Excel and fetches the properties you requested with `load()`.                                                                             |
| `ctx.context`      | The underlying `RequestContext` itself.                                                                                                                                       |

The session works with both `xw.Book` and `xw.BookAsync` (see [Async API](async-api.md)), and it follows these rules:

- **Start:** xlwings writes that are still queued are applied before the session starts, so the session sees them.
- **End:** when the block ends, Office.js code that you haven’t synced yet is synced.
- Only one session can be open at a time.
- Sessions can only be used while a script, notebook cell, or test runs. If one is still open when the run ends, for example in a task that the run didn’t wait for, it’s discarded without applying the Office.js code that wasn’t synced.

## Getting Office.js objects

There are two ways to get Office.js objects:

- **`.api` of xlwings objects**: inside the block, `book.api`, `sheet.api` and `myrange.api` return the Office.js `Workbook`, `Worksheet` and `Range` of an xlwings object. This is useful if you already have the sheet or range as an xlwings object. `sheet.api` finds the sheet by its ID, so it keeps working if the sheet is renamed during the session. Accessing `.api` again on the same sheet or range returns the same Office.js object. For other xlwings objects, such as charts or tables, `.api` doesn’t return Office.js objects: get them from their sheet instead, e.g. `sheet.api.charts.getItem("Revenue")`.
- **`ctx.workbook`**: for everything that starts at the workbook, e.g. `ctx.workbook.worksheets`, `ctx.workbook.names` or `ctx.workbook.getSelectedRange()`.

Outside of a session, `.api` raises an error.

## Working with Office.js objects

Python doesn’t run Office.js code directly. It records your property changes and method calls and sends them to Excel when you call `await ctx.sync()`, following the same batching model as Office.js itself.

### Changes are queued until `await ctx.sync()`

Assignments and method calls only take effect in Excel when you call `await ctx.sync()`, or when the block ends. You only need to sync explicitly if you want to read something.

### Load before reading

To read a property, request it with `load()`, sync, and then read it:

```python
async with book.officejs() as ctx:
    rng = book.sheets[0]["A1:B2"].api
    rng.load("address,values,format/fill/color")
    await ctx.sync()
    print(rng.address, rng.values, rng.format.fill.color)
```

- Use commas to load several properties and `/` for nested properties.
- Reading a property that you haven’t loaded raises an error that tells you which `load()` call is missing. Using an Office.js object itself as a value, e.g. with `print()`, `if`, comparisons, or arithmetic, raises an error, too.
- Loaded values are a snapshot as of the sync: if you change a property afterwards, load it and sync again to read the new value.
- Object-valued properties that aren’t Office.js objects, such as the `rule` of a conditional format, are returned as dictionaries.

### Collections

Load a collection with `items/...` and use its `items` list after the sync:

```python
sheets = ctx.workbook.worksheets
sheets.load("items/name")
await ctx.sync()
for sheet in sheets.items:
    print(sheet.name)
sheets.items[-1].delete()
```

The items in `items` are the real Office.js objects, so you can change them or call their methods. A collection itself can’t be iterated or used with `len()`: use `items`.

### Methods that return values

Methods that return a value rather than an Office.js object, such as `getCount()`, need no `load()`. Read their `value` after the sync:

```python
count = ctx.workbook.worksheets.getCount()
await ctx.sync()
print(count.value)
```

### Objects that may not exist

Methods ending in `OrNullObject`, such as `getItemOrNullObject()`, return an object whose `isNullObject` is set after the sync, also without `load()`:

```python
sheet = ctx.workbook.worksheets.getItemOrNullObject("Archive")
await ctx.sync()
if sheet.isNullObject:
    ctx.workbook.worksheets.add("Archive")
```

### Arguments and values

- Pass arguments by position. Pass option objects as dictionaries, e.g. `sheet.api.protection.protect({"allowFormatCells": True})`. Keyword arguments raise an error.
- Passing more arguments than an Office.js method takes raises an error, because Office.js would silently ignore the extra ones. Set further options as properties of the result instead, e.g. `shape = sheet.api.shapes.addGeometricShape("Rectangle")`, then `shape.left = 100`.
- Arguments and assigned values must be `str`, `int`, `float`, `bool`, `None`, lists and dictionaries of those, or Office.js objects. NumPy numbers and booleans work as well. Convert NumPy arrays with `.tolist()`, e.g. `rng.values = df.values.tolist()`, and dates to strings or numbers.
- `NaN` and infinity can’t be sent and raise an error. For an empty cell, use `""`.
- Values are checked when you assign them or call the method, before anything is sent to Excel.

### After the session

After the block, you can still read properties that you loaded and synced inside it, including collection items. Everything else, such as changing a property or calling a method, raises an error.

## xlwings inside a session

While a session is open, xlwings itself can’t read from or write to Excel: setting `myrange.value`, adding a sheet, `await myrange.get_value()` or `await book.load()` raise an error. Do this before or after the block, or through Office.js inside it.

Values that xlwings loaded before the session, e.g. for `myrange.value` with `xw.Book`, don’t show the changes that you make through Office.js until the block ends. When the block ends, xlwings reloads the workbook if the session changed anything, so xlwings code after the block sees the changes:

- With `xw.Book`, everything is reloaded, including the cell values.
- With `xw.BookAsync`, the workbook structure, such as the sheet names, is reloaded. Read cell values again with `await myrange.get_value()`.

## Errors

When Excel rejects a sync, or when the recorded code can’t run, e.g. because a method doesn’t exist, xlwings raises an `xw.OfficeJsError`, which is a subclass of `xw.XlwingsError`. Its `code` attribute holds the Office.js error code, such as `ItemNotFound`. For mistakes in the recorded code, the message also names the failing expression. For example, to ignore a sheet that doesn’t exist:

```python
try:
    async with book.officejs() as ctx:
        ctx.workbook.worksheets.getItem("Archive").delete()
except xw.OfficeJsError as e:
    if e.code != "ItemNotFound":
        raise
```

To check whether an object exists, `getItemOrNullObject()` is usually simpler, see [Objects that may not exist]().

If the block raises an exception, Office.js code that hasn’t been synced is discarded. What was synced before stays applied.

#### IMPORTANT
A failed sync isn’t transactional: when Excel rejects a sync, the changes that came before the failing one in the same sync may already be applied. After a failed sync, the session can’t sync anymore and discards its remaining unsynced code when the block ends.

## Undo

Each sync, including the final one at the end of the block, is one step in Excel’s undo history. To undo a session with two syncs and unsynced changes at the end of the block, click **Undo** three times.
