Async API
To interact with the Excel object model, scripts and notebooks let you use the same syntax as the classic, locally installed xlwings (sync API). This often works fine, but because xlwings Lite runs in a browser, it talks to Excel differently. That difference creates three limitations, and the async API gives you a method to work around each one:
Loading of cell values. Getting a sync book (
xw.books.activefor notebooks or using thexw.Booktype hint in scripts) fetches all values from the entire workbook, which can be slow and may cause the browser to run out of memory for large workbooks.→
await myrange.get_value()with an asyncBookreads only the values you ask for, and there’s aget_*()method for everything else that isn’t sent up front.Writes are queued. When you assign a value to a range, for example, it’s only applied at the end of a notebook cell or when a script finishes, not immediately. Async reads such as
await myrange.get_value()apply queued writes first, so they always see your earlier changes.→
await book.flush()applies queued writes immediately, even when nothing reads them.Reads can be outdated. Anything you read via the sync API reflects the workbook state from the start of the notebook cell or the start of the script.
→
await book.load()refreshes everything.
The following sections cover each method in detail.
get_value(): reading values on demand
To read values on demand:
Use an async
Bookobject, which disables the loading of all values up front:Notebook:
await xw.books.get_active()Script:
xw.BookAsync(type hint)
Use
await myrange.get_value()instead ofmyrange.valueto load the values live.
In the following example, only the value of a single cell is loaded, no matter how big the workbook is:
# %%
import xlwings as xw
book = await xw.books.get_active() # sync version: book = xw.books.active
myrange = book.sheets[0]["A1"]
await myrange.get_value() # sync version: myrange.value
import xlwings as xw
from xlwings import script
@script
async def my_script(book: xw.BookAsync): # sync version: def my_script(book: xw.Book)
myrange = book.sheets[0]["A1"]
await myrange.get_value() # sync version: myrange.value
Note
Notebooks let you
awaitat the top level without requiring anasync def.Scripts must use
awaitinside of anasync def.
get_value() respects the same converters and options as value, so you can, for example, read a range directly into a pandas DataFrame:
import pandas as pd
df = await (
book.sheets["Sheet1"]["A1:C10"]
.options(pd.DataFrame, index=False)
.get_value()
)
While await get_value() technically also works with a sync book to get the current values, a sync book still loads the whole workbook up front.
get_value() is the one you’ll reach for most, but everything that isn’t sent up front follows the same pattern: await myobject.get_something() instead of myobject.something. Reading an unavailable sync property raises an error pointing at the async method.
flush(): writing immediately
When writing to a workbook, xlwings Lite queues every action and applies them in order at the end of a notebook cell or when the script finishes. With xlwings 0.37.7+, every async read—await myrange.get_value(), the other get_*() methods, and await book.load() or await mysheet.load()—flushes the queued actions first. A read therefore always sees your earlier changes, including a sheet you just added, without an explicit flush:
# %%
book = await xw.books.get_active()
book.sheets[0]["A1"].value = "Hello xlwings!"
await book.sheets[0]["A1"].get_value()
# Output
# 'Hello xlwings!'
import xlwings as xw
from xlwings import script
@script
async def my_script(book: xw.BookAsync):
book.sheets[0]["A1"].value = "Hello xlwings!"
print(await book.sheets[0]["A1"].get_value())
# prints 'Hello xlwings!'
You only need to call await book.flush() explicitly in the following cases:
Showing progress during a long-running script or notebook cell: a change that nothing reads, such as a status message written to a cell, only appears in Excel at the end unless you flush it. Likewise, use
await book.flush()afterprint()to see the printed output immediately in the Output pane.import asyncio import xlwings as xw from xlwings import script @script async def my_script(book: xw.BookAsync): status = book.sheets[0]["A1"] regions = ["North", "South", "East"] for i, region in enumerate(regions, start=1): status.value = f"Processing {i} of {len(regions)}..." print(f"Processing {region}") await book.flush() # Shows the status and the printed output now await asyncio.sleep(2) # Stands in for a slow step status.value = "Done"
Reading a file that an action creates: methods that write to the file system, such as
mysheet["A1:D10"].to_png("/data/range.png")ormychart.to_png("/data/chart.png"), are queued like other actions, and reading the file doesn’t flush them. Callawait book.flush()before accessing the file in the same notebook cell or script.Choosing what’s applied if a script fails: if a script raises an exception, its queued actions are discarded, but everything that was flushed before—explicitly or by an async read—stays applied. Flush to apply your changes up to a certain point, for example, before a step that may fail.
load(): reading the current workbook state
Before running a script or a notebook cell, xlwings Lite automatically runs await book.load(), so you rarely need to call it explicitly. To refresh the workbook state midway through a notebook cell or script, use await book.load() or await mysheet.load():
# %%
book = await xw.books.get_active()
sheet1 = book.sheets[0]
await book.load() # or: await sheet1.load()
sheet1.tables
import xlwings as xw
from xlwings import script
@script
async def my_script(book: xw.BookAsync):
sheet1 = book.sheets[0]
await book.load() # or: await sheet1.load()
sheet1.tables
A few things to keep in mind:
On an async book,
await book.load()fetches everything except values since you should access values viaawait myrange.get_value(). On a sync book,await book.load()includes values. If you want to exclude values on a sync book, useawait book.load(values=False).Calling
load()on a sheet object rather than the book loads only that sheet instead of the whole book, so it’s slightly more efficient.Like other async reads,
load()flushes queued actions first, so the loaded state includes your earlier changes, such as the columns of a table you just added.