Custom Scripts¶
Custom scripts can be connected to buttons on either the Ribbon or the task pane. They are the equivalent to a Sub in VBA or an Office Script.
Basic syntax¶
As you can see in the included sample under custom_scripts/scripts.py, the simplest custom script requires:
the
@scriptdecoratora function argument with the
xw.Booktype hint
Here is how this looks:
import xlwings as xw
from xlwings import script
@script
def hello_world(book: xw.Book):
sheet = book.sheets[0]
sheet["A1"].value = "Hello xlwings!"
Adding New Modules¶
You can add your custom scripts to the scripts.py module. You can, however, also create new modules:
Add a Python module under
custom_functions, e.g.,myscripts.py.Add the following import statement to
custom_functions/__init__.py:from .myscripts import *
Run Custom Scripts¶
You can bind a custom script to buttons in various places:
Configuration¶
To configure scripts, you can provide the decorator with arguments, e.g.:
import xlwings as xw
from xlwings import script
@script(include=["Sheet1", "Sheet2"])
def hello_world(book: xw.Book):
sheet = book.sheets[0]
sheet["A1"].value = "Hello xlwings!"
Here are the settings that you can provide:
exclude(optional): By default, xlwings sends over the content of the whole workbook to the server. If you have sheets with big amounts of data, this can make the calls slow or timeout. If your backend doesn’t need the content of certain sheets, the exclude option will block the sheet’s content (e.g., values, pictures, etc.) from being sent to the backend. Currently, you can only exclude entire sheets like so:exclude=["Sheet1", "Sheet2"].include(optional): It’s the counterpart to exclude and allows you to submit the names of the sheets whose content (e.g., values, pictures, etc.) you want to send to the server. Currently, you can only include entire sheets like so:include=["Sheet1", "Sheet2"].required_roles(optional): This allows you to require certain roles for a user to be able to execute the script, see Authorization and RBAC.button(optional): If you want to use a sheet button, you need to provide the reference for the button and its linked cell, e.g.,button=[mybutton]Sheet1!A1.show_taskpane(optional): Use this in connection withbutton. Ifshow_taskpane=True, the task pane will automatically show up when the user clicks on a sheet button.
Limitations¶
Currently, custom scripts don’t accept arguments other than the special type-hinted ones (xw.Book and xlwings_server.models.CurrentUser).