docs-xlwings-org-en-0.11.8
docs-xlwings-org-en-0.11.8
Release dev
2 Migrate to v0.9 3
2.1 Full qualification: Using collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Connecting to Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Active Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Round vs. Square Brackets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.5 Access the underlying Library/Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.6 Cheat sheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 Installation 7
3.1 Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Optional Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Add-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4 Python version support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4 Quickstart 9
4.1 1. Scripting: Automate/interact with Excel from Python . . . . . . . . . . . . . . . . . . . 9
4.2 2. Macros: Call Python from Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.3 3. UDFs: User Defined Functions (Windows only) . . . . . . . . . . . . . . . . . . . . . . 11
5 Connect to a Book 13
5.1 Python to Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.2 Excel to Python (RunPython) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5.3 User Defined Functions (UDFs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
6 Syntax Overview 15
6.1 Active Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
6.2 Full qualification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6.3 Range indexing/slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
i
6.4 Range Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6.5 Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
8 Add-in 23
8.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
8.2 Global Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8.3 Global Config: Ribbon/Config File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8.4 Workbook Directory Config: Config file . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
8.5 Workbook Config: xlwings.conf Sheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
8.6 Alternative: Standalone VBA module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
8.7 Log File default locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
9 VBA: RunPython 27
9.1 xlwings add-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
9.2 Call Python with “RunPython” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
9.3 Function Arguments and Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
11 Debugging 37
11.1 RunPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
11.2 UDF debug server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
12 Matplotlib 41
12.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12.2 Full integration with Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12.3 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
12.4 Getting a Matplotlib figure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
ii
13.1 Default Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
13.2 Built-in Converters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
13.3 Custom Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
15 Missing Features 57
15.1 Example: Workaround to use VBA’s Range.WrapText . . . . . . . . . . . . . . . . . . 57
17 Extensions 63
17.1 In-Excel SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
18 Troubleshooting 65
18.1 Issue: dll not found . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
19 API Documentation 67
19.1 Top-level functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
19.2 Object model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
19.3 UDF decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
20 License 97
iii
iv
CHAPTER 1
This migration guide shows you how you can start using the new xlwings add-in as opposed to the old
xlwings VBA module (and the old add-in that consisted of just a single import button).
2. If you installed xlwings with pip, for once, you should first uninstall xlwings: pip uninstall
xlwings
3. Check the directory that you got under 1): if there are any files left over, delete the xlwings folder
and the remaining files manually
4. Install the latest xlwings version: pip install xlwings
5. Verify that you have >= 0.11 by doing
1. If you have the old xlwings addin installed, find the location and remove it or overwrite it with the
new version (see next step). If you installed it via the xlwings command line client, you should be
1
xlwings - Make Excel Fly!, Release dev
Migrate to v0.9
The purpose of this document is to enable you a smooth experience when upgrading to xlwings v0.9.0 and
above by laying out the concept and syntax changes in detail. If you want to get an overview of the new
features and bug fixes, have a look at the release notes. Note that the syntax for User Defined Functions
(UDFs) didn’t change.
The new object model allows to specify the Excel application instance if needed:
• old: xw.Range('Sheet1', 'A1', wkb=xw.Workbook('Book1'))
• new: xw.apps[0].books['Book1'].sheets['Sheet1'].range('A1')
See Syntax Overview for the details of the new object model.
• old: xw.Workbook()
• new: xw.Book() or via xw.books if you need to control the app instance.
See Connect to a Book for the details.
3
xlwings - Make Excel Fly!, Release dev
# Active book
>>> wb = xw.books.active # in active app
>>> wb = app.books.active # in specific app
# Active sheet
>>> sht = xw.sheets.active # in active book
>>> sht = wb.sheets.active # in specific book
Round brackets follow Excel’s behavior (i.e. 1-based indexing), while square brackets use Python’s 0-based
indexing/slicing.
As an example, the following all reference the same range:
xw.apps[0].books[0].sheets[0].range('A1')
xw.apps(1).books(1).sheets(1).range('A1')
xw.apps[0].books['Book1'].sheets['Sheet1'].range('A1')
xw.apps(1).books('Book1').sheets('Sheet1').range('A1')
Note that sht stands for a sheet object, like e.g. (in 0.9.0 syntax): sht = xw.books['Book1'].
sheets[0]
v0.9.0 v0.7.2
Active Excel instance xw.apps.active unsupported
New Excel instance app = xw.App() unsupported
Installation
or conda:
Note that the official conda package might be few releases behind. You can, however, use the
conda-forge channel (see: https://anaconda.org/conda-forge/xlwings) which should usually be up to
date (but might still be a day or so behind the pip release):
Note: When you are using Mac Excel 2016 and are installing xlwings with conda (or use the version
that comes with Anaconda), you’ll need to run $ xlwings runpython install once to enable the
RunPython calls from VBA. Alternatively, you can simply install xlwings with pip.
3.1 Dependencies
7
xlwings - Make Excel Fly!, Release dev
On Mac, the dependencies are automatically being handled if xlwings is installed with conda or
pip. However, with pip, the Xcode command line tools need to be available. Mac OS X 10.4 (Tiger)
or later is required. The recommended Python distribution for Mac is Anaconda.
• NumPy
• Pandas
• Matplotlib
• Pillow/PIL
These packages are not required but highly recommended as they play very nicely with xlwings.
3.3 Add-in
8 Chapter 3. Installation
CHAPTER 4
Quickstart
This guide assumes you have xlwings already installed. If that’s not the case, head over to Installation.
If you have the same file open in two instances of Excel, you need to fully qualify it and include the app
instance:
>>> xw.apps[0].books['FileName.xlsx']
9
xlwings - Make Excel Fly!, Release dev
>>> sht.range('A1').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
>>> sht.range('A1').expand().value
[['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
Powerful converters handle most data types of interest, including Numpy arrays and Pandas DataFrames
in both directions:
Note: You should only use xw.Range when interacting with Excel. In scripts, you should always go via
book and sheet objects as shown above.
You can call Python functions from VBA using the RunPython function:
Sub HelloWorld()
RunPython ("import hello; hello.world()")
End Sub
Per default, RunPython expects hello.py in the same directory as the Excel file. Refer to the calling
Excel book by using xw.Book.caller:
10 Chapter 4. Quickstart
xlwings - Make Excel Fly!, Release dev
# hello.py
import numpy as np
import xlwings as xw
def world():
wb = xw.Book.caller()
wb.sheets[0].range('A1').value = 'Hello World!'
To make this run, you’ll need to have the xlwings add-in installed. The easiest way to get everything set
up is to use the xlwings command line client from either a command prompt on Windows or a terminal on
Mac: xlwings quickstart myproject.
For details about the addin, see Add-in.
import xlwings as xw
@xw.func
def hello(name):
return 'Hello {0}'.format(name)
Converters can be used with UDFs, too. Again a Pandas DataFrame example:
import xlwings as xw
import pandas as pd
@xw.func
@xw.arg('x', pd.DataFrame)
def correl2(x):
# x arrives as DataFrame
return x.corr()
Import this function into Excel by clicking the import button of the xlwings add-in: For further details, see
VBA: User Defined Functions (UDFs).
12 Chapter 4. Quickstart
CHAPTER 5
Connect to a Book
When reading/writing data to the active sheet, you don’t need a book object:
The easiest way to connect to a book is offered by xw.Book: it looks for the book in all app instances and
returns an error, should the same book be open in multiple instances. To connect to a book in the active app
instance, use xw.books and to refer to a specific app, use:
xw.Book xw.books
New book xw.Book() xw.books.add()
Unsaved book xw.Book('Book1') xw.books['Book1']
Book by xw.Book(r'C:/path/to/ xw.books.open(r'C:/path/to/
(full)name file.xlsx') file.xlsx')
Note: When specifying file paths on Windows, you should either use raw strings by putting an r in front
of the string or use double back-slashes like so: C:\\path\\to\\file.xlsx.
13
xlwings - Make Excel Fly!, Release dev
To reference the calling book when using RunPython in VBA, use xw.Book.caller(), see Call
Python with “RunPython”. Check out the section about Debugging to see how you can call a script from
both sides, Python and Excel, without the need to constantly change between xw.Book.caller() and
one of the methods explained above.
Unlike RunPython, UDFs don’t need a call to xw.Book.caller(), see VBA: User Defined Functions
(UDFs). However, it’s available (restricted to read-only though), which sometimes proofs to be useful.
Syntax Overview
The xlwings object model is very similar to the one used by VBA.
All code samples below depend on the following import:
# Active book
>>> wb = xw.books.active # in active app
>>> wb = app.books.active # in specific app
# Active sheet
>>> sht = xw.sheets.active # in active book
>>> sht = wb.sheets.active # in specific book
A Range can be instantiated with A1 notation, a tuple of Excel’s 1-based indices, a named range or two
Range objects:
xw.Range('A1')
xw.Range('A1:C3')
xw.Range((1,1))
(continues on next page)
15
xlwings - Make Excel Fly!, Release dev
Round brackets follow Excel’s behavior (i.e. 1-based indexing), while square brackets use Python’s 0-based
indexing/slicing. As an example, the following expressions all reference the same range:
xw.apps[0].books[0].sheets[0].range('A1')
xw.apps(1).books(1).sheets(1).range('A1')
xw.apps[0].books['Book1'].sheets['Sheet1'].range('A1')
xw.apps(1).books('Book1').sheets('Sheet1').range('A1')
Sheet objects offer a shortcut for range objects by using index/slice notation on the sheet object. This evalu-
ates to either sheet.range or sheet.cells depending on whether you pass a string or indices/slices:
The following shows an example of the object hierarchy, i.e. how to get from an app to a range object and
all the way back:
This tutorial gives you a quick introduction to the most common use cases and default behaviour of xlwings
when reading and writing values. For an in-depth documentation of how to control the behavior using the
options method, have a look at Converters and Options.
All code samples below depend on the following import:
Single cells are by default returned either as float, unicode, None or datetime objects, depending
on whether the cell contains a number, a string, is empty or represents a date:
19
xlwings - Make Excel Fly!, Release dev
7.2 Lists
• 1d lists: Ranges that represent rows or columns in Excel are returned as simple lists, which means
that once they are in Python, you’ve lost the information about the orientation. If that is an issue, the
next point shows you how to preserve this info:
>>> sht.range('A1').options(ndim=1).value
[1.0]
• 2d lists: If the row or column orientation has to be preserved, set ndim in the Range options. This
will return the Ranges as nested lists (“2d lists”):
>>> sht.range('A1:A5').options(ndim=2).value
[[1.0], [2.0], [3.0], [4.0], [5.0]]
>>> sht.range('A1:E1').options(ndim=2).value
[[1.0, 2.0, 3.0, 4.0, 5.0]]
• 2 dimensional Ranges are automatically returned as nested lists. When assigning (nested) lists to a
Range in Excel, it’s enough to just specify the top left cell as target address. This sample also makes
use of index notation to read the values back into Python:
>>> sht.range('A10').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10, 20, 30]]
>>> sht.range((10,1),(11,3)).value
[['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
Note: Try to minimize the number of interactions with Excel. It is always more efficient to do
sht.range('A1').value = [[1,2],[3,4]] than sht.range('A1').value = [1, 2]
and sht.range('A2').value = [3, 4].
You can get the dimensions of Excel Ranges dynamically through either the method expand or through the
expand keyword in the options method. While expand gives back an expanded Range object, options
are only evaluated when accessing the values of a Range. The difference is best explained with an example:
>>> sht = xw.Book().sheets[0]
>>> sht.range('A1').value = [[1,2], [3,4]]
>>> rng1 = sht.range('A1').expand('table') # or just .expand()
>>> rng2 = sht.range('A1').options(expand='table')
>>> rng1.value
[[1.0, 2.0], [3.0, 4.0]]
>>> rng2.value
[[1.0, 2.0], [3.0, 4.0]]
>>> sht.range('A3').value = [5, 6]
>>> rng1.value
[[1.0, 2.0], [3.0, 4.0]]
>>> rng2.value
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]
'table' expands to 'down' and 'right', the other available options which can be used for column or
row only expansion, respectively.
Note: Using expand() together with a named Range as top left cell gives you a flexible setup in Excel:
You can move around the table and change it’s size without having to adjust your code, e.g. by using
something like sht.range('NamedRange').expand().value.
NumPy arrays work similar to nested lists. However, empty cells are represented by nan instead of None.
If you want to read in a Range as array, set convert=np.array in the options method:
>>> import numpy as np
>>> sht = xw.Book().sheets[0]
>>> sht.range('A1').value = np.eye(3)
>>> sht.range('A1').options(np.array, expand='table').value
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Note: You only need to specify the top left cell when writing a list, a NumPy array or a Pandas DataFrame
to Excel, e.g.: sht.range('A1').value = np.eye(10)
Add-in
The xlwings add-in is the preferred way to be able to use RunPython or UDFs. Note that you don’t need
an add-in if you just want to manipulate Excel from Python via xlwings.
Note: The ribbon of the add-in is compatible with Excel >= 2007 on Windows and >= 2016 on Mac. You
could, however, use the add-in with earlier versions but you would need to change the settings directly in
the config file, see below. On Mac, all UDF related functionality is not available.
Note: The add-in is password protected with the password xlwings. For debugging or to add new
extensions, you need to unprotect it.
8.1 Installation
To install the add-in, it’s easiest to use the command line client: xlwings addin install.
Then, to use RunPython or UDFs in a workbook, you need to set a reference to xlwings in the VBA
editor, see screenshot (Windows: Tools > References..., Mac: it’s on the lower left corner of the
23
xlwings - Make Excel Fly!, Release dev
VBA editor). Note that when you create a workbook via xlwings quickstart, the reference is already
set.
While the defaults will often work out-of-the box, you can change the global settings directly in the add-in:
• Interpreter: This is the path to the Python interpreter (works also with virtual or conda envs),
e.g. "C:\Python35\pythonw.exe" or "/usr/local/bin/python3.5". An empty
field defaults to pythonw that expects the interpreter to be set in the PATH on Windows or .
bash_profile on Mac.
• PYTHONPATH: If the source file of your code is not found, add the path here.
• UDF_MODULES: Names of Python modules (without .py extension) from which the UDFs are be-
ing imported. Separate multiple modules by “;”. Example: UDF_MODULES = "common_udfs;
myproject" The default imports a file in the same directory as the Excel spreadsheet with the same
name but ending in .py.
• Debug UDFs: Check this box if you want to run the xlwings COM server manually for debugging,
see Debugging.
• Log File: Leave empty for default location (see below) or provide the full path, e.g. .
• RunPython: Use UDF Server: Uses the same COM Server for RunPython as for UDFs. This
will be faster, as the interpreter doesn’t shut down after each call.
• Restart UDF Server: This shuts down the UDF Server/Python interpreter. It’ll be restarted
upon the next function call.
The settings in the xlwings Ribbon are stored in a config file that can also be manipulated externally. The
location is
• Windows: .xlwings\xlwings.conf in your user folder
• Mac Excel 2016: ~/Library/Containers/com.microsoft.Excel/Data/xlwings.
conf
24 Chapter 8. Add-in
xlwings - Make Excel Fly!, Release dev
"INTERPRETER","pythonw"
"PYTHONPATH",""
Note: Mac Excel 2011 users have to create and edit the config file manually under ~/.xlwings/
xlwings.conf as the ribbon is not supported.
The global settings of the Ribbon/Config file can be overridden for one or more workbooks by creating a
xlwings.conf file in the workbook’s directory.
Workbook specific settings will override global (Ribbon) and workbook directory config files: Workbook
specific settings are set by listing the config key/value pairs in a sheet with the name xlwings.conf.
When you create a new project with xlwings quickstart, it’ll already have such a sheet but you need
to rename it to xlwings.conf to make it active.
Sometimes it might be useful to run xlwings code without having to install an add-in first. To do so, you need
to use the standalone option when creating a new project: xlwings quickstart myproject
--standalone.
This will add the content of the add-in as a single VBA module so you don’t need to set a reference to the
add-in anymore. It will still read in the settings from your xlwings.conf if you don’t override them by
using a sheet with the name xlwings.conf.
These log files are used for the error pop-up windows:
• Windows: %APPDATA%\xlwings.log
• Mac with Excel 2011: /tmp/xlwings.log
• Mac with Excel 2016: ~/Library/Containers/com.microsoft.Excel/Data/
xlwings.log
26 Chapter 8. Add-in
CHAPTER 9
VBA: RunPython
To get access to the RunPython function, you’ll need the xlwings addin (or VBA module), see Add-in.
For new projects, the easiest way to get started is by using the command line client with the quickstart
command, see Command Line Client for details:
In the VBA Editor (Alt-F11), write the code below into a VBA module. xlwings quickstart
automatically adds a new module with a sample call. If you rather want to start from scratch, you can add
new module via Insert > Module.
Sub HelloWorld()
RunPython ("import hello; hello.world()")
End Sub
# hello.py
import numpy as np
import xlwings as xw
def world():
wb = xw.Book.caller()
wb.sheets[0].range('A1').value = 'Hello World!'
27
xlwings - Make Excel Fly!, Release dev
You can then attach HelloWorld to a button or run it directly in the VBA Editor by hitting F5.
Note: Place xw.Book.caller() within the function that is being called from Excel and not outside as
global variable. Otherwise it prevents Excel from shutting down properly upon exiting and leaves you with
a zombie process when you use OPTIMIZED_CONNECTION = True.
While it’s technically possible to include arguments in the function call within RunPython, it’s not very
convenient. Also, RunPython does not allow you to return values. To overcome these issue, use UDFs,
see VBA: User Defined Functions (UDFs) - however, this is currently limited to Windows only.
This tutorial gets you quickly started on how to write User Defined Functions.
Note:
• UDFs are currently only available on Windows.
• For details of how to control the behaviour of the arguments and return values, have a look at Con-
verters and Options.
• For a comprehensive overview of the available decorators and their options, check out the correspond-
ing API docs: UDF decorators.
1) Enable Trust access to the VBA project object model under File > Options >
Trust Center > Trust Center Settings > Macro Settings
2. Install the add-in via command prompt: xlwings addin install (see Add-in).
The easiest way to start a new project is to run xlwings quickstart myproject on a command
prompt (see Command Line Client). This automatically adds the xlwings reference to the generated work-
book.
29
xlwings - Make Excel Fly!, Release dev
The default addin settings expect a Python source file in the way it is created by quickstart:
• in the same directory as the Excel file
• with the same name as the Excel file, but with a .py ending instead of .xlsm.
Alternatively, you can point to a specific module via UDF Modules in the xlwings ribbon.
Let’s assume you have a Workbook myproject.xlsm, then you would write the following code in
myproject.py:
import xlwings as xw
@xw.func
def double_sum(x, y):
"""Returns twice the sum of the two arguments"""
return 2 * (x + y)
• Now click on Import Python UDFs in the xlwings tab to pick up the changes made to
myproject.py.
• Enter the formula =double_sum(1, 2) into a cell and you will see the correct result:
Note:
• You only need to re-import your functions if you change the function arguments or the function name.
• Code changes in the actual functions are picked up automatically (i.e. at the next calculation of the
formula, e.g. triggered by Ctrl-Alt-F9), but changes in imported modules are not. This is the
very behaviour of how Python imports work. If you want to make sure everything is in a fresh state,
click Restart UDF Server.
• The @xw.func decorator is only used by xlwings when the function is being imported into Excel. It
tells xlwings for which functions it should create a VBA wrapper function, otherwise it has no effect
on how the functions behave in Python.
Calling one big array formula in Excel is much more efficient than calling many single-cell formulas, so it’s
generally a good idea to use them, especially if you hit performance problems.
You can pass an Excel Range as a function argument, as opposed to a single cell and it will show up in
Python as list of lists.
For example, you can write the following function to add 1 to every cell in a Range:
@xw.func
def add_one(data):
return [[cell + 1 for cell in row] for row in data]
The above formula has the issue that it expects a “two dimensional” input, e.g. a nested list of the form [[1,
2], [3, 4]]. Therefore, if you would apply the formula to a single cell, you would get the following
error: TypeError: 'float' object is not iterable.
To force Excel to always give you a two-dimensional array, no matter whether the argument is a single cell,
a column/row or a two-dimensional Range, you can extend the above formula like this:
@xw.func
@xw.arg('data', ndim=2)
def add_one(data):
return [[cell + 1 for cell in row] for row in data]
Often, you’ll want to use NumPy arrays or Pandas DataFrames in your UDF, as this unlocks the full power
of Python’s ecosystem for scientific computing.
To define a formula for matrix multiplication using numpy arrays, you would define the following function:
import xlwings as xw
import numpy as np
@xw.func
@xw.arg('x', np.array, ndim=2)
@xw.arg('y', np.array, ndim=2)
def matrix_mult(x, y):
return x @ y
Note: If you are not on Python >= 3.5 with NumPy >= 1.10, use x.dot(y) instead of x @ y.
A great example of how you can put Pandas at work is the creation of an array-based CORREL formula.
Excel’s version of CORREL only works on 2 datasets and is cumbersome to use if you want to quickly
get the correlation matrix of a few time-series, for example. Pandas makes the creation of an array-based
CORREL2 formula basically a one-liner:
import xlwings as xw
import pandas as pd
@xw.func
@xw.arg('x', pd.DataFrame, index=False, header=False)
@xw.ret(index=False, header=False)
def CORREL2(x):
"""Like CORREL, but as array formula for more than 2 data sets"""
return x.corr()
These decorators are to UDFs what the options method is to Range objects: they allow you to apply
converters and their options to function arguments (@xw.arg) and to the return value (@xw.ret). For
example, to convert the argument x into a pandas DataFrame and suppress the index when returning it, you
would do the following:
@xw.func
@xw.arg('x', pd.DataFrame)
@xw.ret(index=False)
def myfunction(x):
# x is a DataFrame, do something with it
return x
As seen above, to use Excel’s array formulas, you need to specify their dimensions up front by selecting
the result array first, then entering the formula and finally hitting Ctrl-Shift-Enter. While this makes
sense from a data integrity point of view, in practice, it often turns out to be a cumbersome limitation,
especially when working with dynamic arrays such as time series data. Since v0.10, xlwings offers dynamic
UDF expansion:
This is a simple example that demonstrates the syntax and effect of UDF expansion:
import numpy as np
@xw.func
@xw.ret(expand='table')
def dynamic_array(r, c):
return np.random.randn(int(r), int(c))
Note:
• Expanding array formulas will overwrite cells without prompting and leave an empty border around
them, i.e. they will clear the row to the bottom and the column to the right of the array.
• The way that dynamic array formulas are currently implemented doesn’t allow them to have volatile
functions as arguments, e.g. you cannot use functions like =TODAY() as arguments.
10.8 Docstrings
The following sample shows how to include docstrings both for the function and for the arguments x and y
that then show up in the function wizard in Excel:
import xlwings as xw
@xw.func
(continues on next page)
10.8. Docstrings 33
xlwings - Make Excel Fly!, Release dev
It’s often helpful to get the address of the calling cell. Right now, one of the easiest ways to accomplish
this is to use the vba keyword. vba, in fact, allows you to access any available VBA expression e.g.
Application. Note, however, that currently you’re acting directly on the pywin32 COM object:
@xw.func
@xw.arg('xl_app', vba='Application')
def get_caller_address(xl_app):
return xl_app.Caller.Address
10.10 Macros
On Windows, as alternative to calling macros via RunPython, you can also use the @xw.sub decorator:
import xlwings as xw
@xw.sub
def my_macro():
"""Writes the name of the Workbook into Range("A1") of Sheet 1"""
wb = xw.Book.caller()
wb.sheets[0].range('A1').value = wb.name
After clicking on Import Python UDFs, you can then use this macro by executing it via Alt + F8 or
by binding it e.g. to a button. To to the latter, make sure you have the Developer tab selected under File
> Options > Customize Ribbon. Then, under the Developer tab, you can insert a button via
Insert > Form Controls. After drawing the button, you will be prompted to assign a macro to it
and you can select my_macro.
Imported functions can also be used from VBA. They return a 2d array:
Sub MySub()
End Sub
Debugging
Since xlwings runs in every Python environment, you can use your preferred way of debugging.
• RunPython: When calling Python through RunPython, you can set a mock_caller to make it
easy to switch back and forth between calling the function from Excel and Python.
• UDFs: For debugging User Defined Functions, xlwings offers a convenient debugging server
To begin with, Excel will show Python errors in a Message Box:
Note: On Mac, if the import of a module/package fails before xlwings is imported, the popup will not
be shown and the StatusBar will not be reset. However, the error will still be logged in the log file. For the
location of the logfile, see Log File default locations.
37
xlwings - Make Excel Fly!, Release dev
11.1 RunPython
Consider the following sample code of your Python source code my_module.py:
# my_module.py
import os
import xlwings as xw
def my_macro():
wb = xw.Book.caller()
wb.sheets[0].range('A1').value = 1
if __name__ == '__main__':
# Expects the Excel file next to this source file, adjust accordingly.
xw.Book('myfile.xlsm').set_mock_caller()
my_macro()
my_macro() can now easily be run from Python for debugging and from Excel via RunPython without
having to change the source code:
Sub my_macro()
RunPython ("import my_module; my_module.my_macro()")
End Sub
Windows only: To debug UDFs, just check the Debug UDFs in the Add-in, at the top of the xlwings VBA
module. Then add the following lines at the end of your Python source file and run it. Depending on which
IDE you use, you might need to run the code in “debug” mode (e.g. in case you’re using PyCharm or
PyDev):
if __name__ == '__main__':
xw.serve()
When you recalculate the Sheet (Ctrl-Alt-F9), the code will stop at breakpoints or output any print calls
that you may have.
The following screenshot shows the code stopped at a breakpoint in the community version of PyCharm:
Note: When running the debug server from a command prompt, there is currently no gracious way to
terminate it, but closing the command prompt will kill it.
Matplotlib
Note: If you set update=True, you can resize and position the plot on Excel: subsequent calls to
pictures.add() with the same name ('MyPlot') will update the picture without changing its position
or size.
Calling the above code with RunPython and binding it e.g. to a button is straightforward and works cross-
platform.
41
xlwings - Make Excel Fly!, Release dev
However, on Windows you can make things feel even more integrated by setting up a UDF along the
following lines:
@xw.func
def myplot(n):
sht = xw.Book.caller().sheets.active
fig = plt.figure()
plt.plot(range(int(n)))
sht.pictures.add(fig, name='MyPlot', update=True)
return 'Plotted with n={}'.format(n)
If you import this function and call it from cell B2, then the plot gets automatically updated when cell B1
changes:
12.3 Properties
Size, position and other properties can either be set as arguments within pictures.add(), or by manip-
ulating the picture object that is returned, see xlwings.Picture().
For example:
or:
12.3. Properties 43
xlwings - Make Excel Fly!, Release dev
Here are a few examples of how you get a matplotlib figure object:
• via PyPlot interface:
or:
• via Pandas:
import pandas as pd
import numpy as np
Introduced with v0.7.0, converters define how Excel ranges and their values are converted both during
reading and writing operations. They also provide a consistent experience across xlwings.Range objects
and User Defined Functions (UDFs).
Converters are explicitely set in the options method when manipulating Range objects or in the @xw.
arg and @xw.ret decorators when using UDFs. If no converter is specified, the default converter is
applied when reading. When writing, xlwings will automatically apply the correct converter (if available)
according to the object’s type that is being written to Excel. If no converter is found for that type, it falls
back to the default converter.
All code samples below depend on the following import:
Syntax:
xw.Range UDFs
read- xw.Range.options(convert=None, @arg('x',
ing **kwargs).value convert=None,
**kwargs)
writ- xw.Range.options(convert=None, @ret(convert=None,
ing **kwargs).value = myvalue **kwargs)
Note: Keyword arguments (kwargs) may refer to the specific converter or the default converter. For
example, to set the numbers option in the default converter and the index option in the DataFrame
converter, you would write:
45
xlwings - Make Excel Fly!, Release dev
• numbers
By default cells with numbers are read as float, but you can change it to int:
>>> sht.range('A1').value = 1
>>> sht.range('A1').value
1.0
>>> sht.range('A1').options(numbers=int).value
1
Alternatively, you can specify any other function or type which takes a single float argument.
Using this on UDFs looks like this:
@xw.func
@xw.arg('x', numbers=int)
def myfunction(x):
(continues on next page)
Note: Excel always stores numbers internally as floats, which is the reason why the int converter
rounds numbers first before turning them into integers. Otherwise it could happen that e.g. 5 might be
returned as 4 in case it is represented as a floating point number that is slightly smaller than 5. Should
you require Python’s original int in your converter, use raw int instead.
• dates
By default cells with dates are read as datetime.datetime, but you can change it to datetime.
date:
– Range:
• empty
Empty cells are converted per default into None, you can change this as follows:
– Range: >>> sht.range('A1').options(empty='NA').value
– UDFs: @xw.arg('x', empty='NA')
• transpose
This works for reading and writing and allows us to e.g. write a list in column orientation to Excel:
– Range: sht.range('A1').options(transpose=True).value = [1, 2, 3]
– UDFs:
@xw.arg('x', transpose=True)
@xw.ret(transpose=True)
def myfunction(x):
# x will be returned unchanged as transposed both when reading
˓→and writing
return x
• expand
This works the same as the Range properties table, vertical and horizontal but is only
evaluated when getting the values of a Range:
Note: The expand method is only available on Range objects as UDFs only allow to manipulate
the calling cells.
xlwings offers several built-in converters that perform type conversion to dictionaries, NumPy arrays,
Pandas Series and DataFrames. These build on top of the default converter, so in most cases the options
described above can be used in this context, too (unless they are meaningless, for example the ndim in the
case of a dictionary).
It is also possible to write and register custom converter for additional types, see below.
The samples below can be used with both xlwings.Range objects and UDFs even though only one
version may be shown.
The dictionary converter turns two Excel columns into a dictionary. If the data is in row orientation, use
transpose:
The same sample for UDF (starting in Range('A13') on screenshot) looks like this:
@xw.func
@xw.arg('x', pd.DataFrame, header=2)
@xw.ret(index=False)
def myfunction(x):
# x is a DataFrame, do something with it
return x
@xw.func
@xw.arg('x', xw.Range)
def myfunction(x):
return x.formula
This returns x as xlwings.Range object, i.e. without applying any converters or options.
• The raw converter delivers the values unchanged from the underlying libraries (pywin32 on Win-
dows and appscript on Mac), i.e. no sanitizing/cross-platform harmonizing of values are being
made. This might be useful in a few cases for efficiency reasons. E.g:
>>> sht.range('A1:B2').value
[[1.0, 'text'], [datetime.datetime(2016, 2, 1, 0, 0), None]]
class MyConverter(Converter):
@staticmethod
def read_value(value, options):
myoption = options.get('myoption', default_value)
return_value = value # Implement your conversion here
return return_value
@staticmethod
def write_value(value, options):
myoption = options.get('myoption', default_value)
return_value = value # Implement your conversion here
return return_value
• Optional: set a base converter (base expects a class name) to build on top of an ex-
isting converter, e.g. for the built-in ones: DictCoverter, NumpyArrayConverter,
PandasDataFrameConverter, PandasSeriesConverter
• Optional: register the converter: you can (a) register a type so that your converter becomes the default
for this type during write operations and/or (b) you can register an alias that will allow you to explicitly
call your converter by name instead of just by class name
The following examples should make it much easier to follow - it defines a DataFrame converter that extends
the built-in DataFrame converter to add support for dropping nan’s:
class DataFrameDropna(Converter):
base = PandasDataFrameConverter
@staticmethod
def read_value(builtin_df, options):
dropna = options.get('dropna', False) # set default to False
if dropna:
converted_df = builtin_df.dropna()
else:
converted_df = builtin_df
# This will arrive in Python when using the DataFrameDropna converter
˓→for reading
return converted_df
@staticmethod
def write_value(df, options):
dropna = options.get('dropna', False)
if dropna:
converted_df = df.dropna()
else:
converted_df = df
# This will be passed to the built-in PandasDataFrameConverter when
˓→writing
return converted_df
# Write
sht.range('A1').value = df
# Read
sht.range('A1:C4').options(pd.DataFrame).value
• DataFrameDropna converter:
# Write
sht.range('A7').options(DataFrameDropna, dropna=True).value = df
# Read
sht.range('A1:C4').options(DataFrameDropna, dropna=True).value
DataFrameDropna.register('df_dropna')
# Write
sht.range('A12').options('df_dropna', dropna=True).value = df
# Read
sht.range('A1:C4').options('df_dropna', dropna=True).value
DataFrameDropna.register(pd.DataFrame)
# Write
sht.range('A13').options(dropna=True).value = df
# Read
sht.range('A1:C4').options(pd.DataFrame, dropna=True).value
@xw.func
@arg('x', DataFrameDropna, dropna=True)
@ret(DataFrameDropna, dropna=True)
def myfunction(x):
# ...
return x
Note: Python objects run through multiple stages of a transformation pipeline when they are being written
to Excel. The same holds true in the other direction, when Excel/COM objects are being read into Python.
Pipelines are internally defined by Accessor classes. A Converter is just a special Accessor which converts
to/from a particular type by adding an extra stage to the pipeline of the default Accessor. For example, the
PandasDataFrameConverter defines how a list of list (as delivered by the default Accessor) should
be turned into a Pandas DataFrame.
The Converter class provides basic scaffolding to make the task of writing a new Converter easier. If you
need more control you can subclass Accessor directly, but this part requires more work and is currently
undocumented.
xlwings comes with a command line client that makes it easy to set up workbooks and install the add-in. On
Windows, type the commands into a Command Prompt, on Mac, type them into a Terminal.
14.1 Quickstart
If you want to use xlwings via VBA module instead of addin, use the --standalone or -s flag:
xlwings quickstart myproject --standalone
14.2 Add-in
The addin command makes it easy on Windows to install/remove the addin. On Mac, you need to install it
manually, but xlwings addin install will show you how to do it.
Note: Excel needs to be closed before installing/updating the add-in via command line. If you’re still
getting an error, start the Task Manager and make sure there are no EXCEL.EXE processes left.
55
xlwings - Make Excel Fly!, Release dev
• xlwings addin install: Copies the xlwings add-in to the XLSTART folder
• xlwings addin update: Replaces the current add-in with the latest one
• xlwings addin remove: Removes the add-in from the XLSTART folder
• xlwings addin status: Shows if the add-in is installed together with the installation path
After installing the add-in, it will be available as xlwings tab on the Excel Ribbon.
New in version 0.6.0.
14.3 RunPython
Only required if you are on Mac, are using Excel 2016 and have xlwings installed via conda or as part of
Anaconda. To enable the RunPython calls in VBA, run this one time:
xlwings runpython install
Alternatively, install xlwings with pip.
New in version 0.7.0.
Missing Features
This works accordingly for the other objects like sht.range('A1').api etc.
The underlying objects will offer you pretty much everything you can do with VBA, using the syntax
of pywin32 (which pretty much feels like VBA) and appscript (which doesn’t feel like VBA). But
apart from looking ugly, keep in mind that it makes your code platform specific (!), i.e. even if you
go for option 2), you should still follow option 1) and open an issue so the feature finds it’s way into
the library (cross-platform and with a Pythonic syntax).
# Windows
sht.range('A1').api.WrapText = True
57
xlwings - Make Excel Fly!, Release dev
While xlwings is a pure Python package, there are cross-language packages that allow for a relative straight-
forward use from/with other languages. This means, however, that you’ll always need to have Python with
xlwings installed in addition to R or Julia. We recommend the Anaconda distribution, see also Installation.
16.1 R
The R instructions are for Windows, but things work accordingly on Mac except that calling the R functions
as User Defined Functions is not supported at the moment (but RunPython works, see Call Python with
“RunPython”).
Setup:
• Install R and Python
• Add R_HOME environment variable to base directory of installation, .e.g C:\Program
Files\R\R-x.x.x
• Add R_USER environment variable to user folder, e.g. C:\Users\<user>
• Add C:\Program Files\R\R-x.x.x\bin to PATH
• Restart Windows because of the environment variables (!)
59
xlwings - Make Excel Fly!, Release dev
import xlwings as xw
import rpy2.robjects as robjects
# you might want to use some relative path or place the file in R's current
˓→working dir
robjects.r.source(r"C:\path\to\r_file.R")
@xw.func
def myfunction(x, y):
myfunc = robjects.r['myfunction']
return tuple(myfunc(x, y))
After importing this function (see: VBA: User Defined Functions (UDFs)), it will be available as UDF from
Excel.
import xlwings as xw
import numpy as np
import rpy2.robjects as robjects
from rpy2.robjects import numpy2ri
robjects.r.source(r"C:\path\to\r_file.R")
numpy2ri.activate()
@xw.func
@xw.arg("x", np.array, ndim=2)
@xw.arg("y", np.array, ndim=2)
def array_function(x, y):
array_func = robjects.r['array_function']
return np.array(array_func(x, y))
After importing this function (see: VBA: User Defined Functions (UDFs)), it will be available as UDF from
Excel.
16.2 Julia
Setup:
• Install Julia and Python
• Run Pkg.add("PyCall") from an interactive Julia interpreter
xlwings can then be called from Julia with the following syntax (the colons take care of automatic type
conversion):
julia> xw.Book()
PyObject <Book [Workbook1]>
16.2. Julia 61
xlwings - Make Excel Fly!, Release dev
Extensions
It’s easy to extend the xlwings add-in with own code like UDFs or RunPython macros, so that they can
be deployed without end users having to import or write the functions themselves. Just add another VBA
module to the xlwings addin with the respective code.
UDF extensions can be used from every workbook without having to set a reference.
The xlwings addin comes with a built-in extension that adds in-Excel SQL syntax (sqlite dialect):
63
xlwings - Make Excel Fly!, Release dev
As this extension uses UDFs, it’s only available on Windows right now.
Troubleshooting
Solution:
1. xlwings32-<version>.dll and xlwings64-<version>.dll are both in the same direc-
tory as your python.exe. If not, something went wrong with your installation. Reinstall it with
pip or conda, see Installation.
2. Check your Interpreter in the add-in or config sheet. If it is empty, then you need to be
able to open a windows command prompt and type python to start an interactive Python session.
If you get the error 'python' is not recognized as an internal or external
command, operable program or batch file., then you have two options: Either add
the path of where your python.exe lives to your Windows path (see https://www.computerhope.
com/issues/ch000549.htm) or set the full path to your interpreter in the add-in or your config sheet,
e.g. C:\Users\MyUser\anaconda\pythonw.exe
65
xlwings - Make Excel Fly!, Release dev
API Documentation
xlwings.view(obj, sheet=None)
Opens a new workbook and displays an object on its first sheet by default. If you provide a sheet
object, it will clear the sheet before displaying the object on the existing sheet.
Parameters
• obj (any type with built-in converter) – the object to display,
e.g. numbers, strings, lists, numpy arrays, pandas dataframes
• sheet (Sheet, default None) – Sheet object. If none provided, the first
sheet of a new workbook is used.
Examples
67
xlwings - Make Excel Fly!, Release dev
19.2.1 Apps
class xlwings.main.Apps(impl)
A collection of all app objects:
active
Returns the active app.
New in version 0.9.0.
add()
Creates a new App. The new App becomes the active one. Returns an App object.
count
Returns the number of apps.
New in version 0.9.0.
19.2.2 App
>>> xw.apps
Apps([<Excel App 1668>, <Excel App 1644>])
>>> xw.apps[0]
<Excel App 1668>
>>> xw.apps.active
<Excel App 1668>
Parameters
• visible (bool, default None) – Returns or sets a boolean value that
determines whether the app is visible. The default leaves the state unchanged or
sets visible=True if the object doesn’t exist yet.
• spec (str, default None) – Mac-only, use the full path to the Excel appli-
cation, e.g. /Applications/Microsoft Office 2011/Microsoft
Excel or /Applications/Microsoft Excel
On Windows, if you want to change the version of Excel that xlwings talks to, go
to Control Panel > Programs and Features and Repair the Of-
fice version that you want as default.
Note: On Mac, while xlwings allows you to run multiple instances of Excel, it’s a feature that is
not officially supported by Excel for Mac: Unlike on Windows, Excel will not ask you to open a
read-only version of a file if it is already open in another instance. This means that you need to watch
out yourself so that the same file is not being overwritten from different instances.
activate(steal_focus=False)
Activates the Excel app.
Parameters steal_focus (bool, default False) – If True, make front-
most application and hand over focus from Python to Excel.
New in version 0.9.0.
api
Returns the native object (pywin32 or appscript obj) of the engine being used.
New in version 0.9.0.
books
A collection of all Book objects that are currently open.
New in version 0.9.0.
calculate()
Calculates all open books.
New in version 0.3.6.
calculation
Returns or sets a calculation value that represents the calculation mode. Modes: 'manual',
'automatic', 'semiautomatic'
Examples
hwnd
Returns the Window handle (Windows-only).
New in version 0.9.0.
kill()
Forces the Excel app to quit by killing its process.
New in version 0.9.0.
macro(name)
Runs a Sub or Function in Excel VBA that are not part of a specific workbook but e.g. are part
of an add-in.
Parameters name (Name of Sub or Function with or without module name, e.g.
'Module1.MyMacro' or 'MyMacro') –
Examples
Function MySum(x, y)
MySum = x + y
End Function
doing, but it will run faster. Remember to set the screen_updating property back to True when
your script ends.
New in version 0.3.3.
selection
Returns the selected cells as Range.
New in version 0.9.0.
version
Returns the Excel version number object.
Examples
19.2.3 Books
class xlwings.main.Books(impl)
A collection of all book objects:
19.2.4 Book
The easiest way to connect to a book is offered by xw.Book: it looks for the book in all app instances
and returns an error, should the same book be open in multiple instances. To connect to a book in the
active app instance, use xw.books and to refer to a specific app, use:
xw.Book xw.books
New book xw.Book() xw.books.add()
Unsaved book xw.Book('Book1') xw.books['Book1']
Book by xw.Book(r'C:/path/to/ xw.books.open(r'C:/path/to/
(full)name file.xlsx') file.xlsx')
Parameters fullname (str, default None) – Full path or name (incl. xlsx, xlsm
etc.) of existing workbook or name of an unsaved workbook. Without a full path, it
looks for the file in the current working directory.
activate(steal_focus=False)
Activates the book.
Parameters steal_focus (bool, default False) – If True, make front-
most window and hand over focus from Python to Excel.
api
Returns the native object (pywin32 or appscript obj) of the engine being used.
New in version 0.9.0.
app
Returns an app object that represents the creator of the book.
New in version 0.9.0.
classmethod caller()
References the calling book when the Python function is called from Excel via RunPython.
Pack it into the function being called from Excel, e.g.:
To be able to easily invoke such code from Python for debugging, use xw.Book.
set_mock_caller().
New in version 0.3.0.
close()
Closes the book without saving it.
New in version 0.1.1.
fullname
Returns the name of the object, including its path on disk, as a string. Read-only String.
macro(name)
Runs a Sub or Function in Excel VBA.
Parameters name (Name of Sub or Function with or without module name, e.g.
'Module1.MyMacro' or 'MyMacro') –
Examples
Function MySum(x, y)
MySum = x + y
End Function
static open_template()
Creates a new Excel file with the xlwings VBA module already included. This method must be
called from an interactive Python shell:
>>> xw.Book.open_template()
Example
Examples
# This code runs unchanged from Excel via RunPython and from Python
˓→directly
import os
import xlwings as xw
def my_macro():
sht = xw.Book.caller().sheets[0]
sht.range('A1').value = 'Hello xlwings!'
if __name__ == '__main__':
xw.Book('file.xlsm').set_mock_caller()
my_macro()
sheets
Returns a sheets collection that represents all the sheets in the book.
New in version 0.9.0.
19.2.5 Sheets
class xlwings.main.Sheets(impl)
A collection of all sheet objects:
19.2.6 Sheet
activate()
Activates the Sheet and returns it.
api
Returns the native object (pywin32 or appscript obj) of the engine being used.
New in version 0.9.0.
autofit(axis=None)
Autofits the width of either columns, rows or both on a whole Sheet.
Parameters axis (string, default None) –
• To autofit rows, use one of the following: rows or r
• To autofit columns, use one of the following: columns or c
• To autofit rows and columns, provide no arguments
Examples
name
Gets or sets the name of the Sheet.
names
Returns a names collection that represents all the sheet-specific names (names defined with the
“SheetName!” prefix).
New in version 0.9.0.
pictures
See Pictures
New in version 0.9.0.
range(cell1, cell2=None)
Returns a Range object from the active sheet of the active book, see Range().
New in version 0.9.0.
select()
Selects the Sheet. Select only works on the active book.
New in version 0.9.0.
shapes
See Shapes
New in version 0.9.0.
19.2.7 Range
Examples
Active Sheet:
import xlwings as xw
xw.Range('A1')
xw.Range('A1:C3')
xw.Range((1,1))
(continues on next page)
Specific Sheet:
xw.books['MyBook.xlsx'].sheets[0].range('A1')
Returns RGB
Return type tuple
Examples
combination of blank rows and blank columns or the edges of the worksheet. It corresponds to
Ctrl-* on Windows and Shift-Ctrl-Space on Mac.
Returns
Return type Range object
end(direction)
Returns a Range object that represents the cell at the end of the region that contains the source
range. Equivalent to pressing Ctrl+Up, Ctrl+down, Ctrl+left, or Ctrl+right.
Parameters direction (One of 'up', 'down', 'right', 'left') –
Examples
Examples
formula_array
Gets or sets an array formula for the given Range.
New in version 0.7.1.
get_address(row_absolute=True, column_absolute=True, include_sheetname=False, ex-
ternal=False)
Returns the address of the range in the specified format. address can be used instead if none
of the defaults need to be changed.
Parameters
• row_absolute (bool, default True) – Set to True to return the row
part of the reference as an absolute reference.
• column_absolute (bool, default True) – Set to True to return the
column part of the reference as an absolute reference.
• include_sheetname (bool, default False) – Set to True to include
the Sheet name in the address. Ignored if external=True.
• external (bool, default False) – Set to True to return an external
reference with workbook and worksheet name.
Returns
Return type str
Examples
Examples
Example
Examples
Parameters
• row_size (int > 0) – The number of rows in the new range (if None, the
number of rows in the range is unchanged).
• column_size (int > 0) – The number of columns in the new range (if
None, the number of columns in the range is unchanged).
Returns Range object
Return type Range
New in version 0.3.0.
row
Returns the number of the first row in the specified range. Read-only.
Returns
Return type Integer
New in version 0.3.5.
row_height
Gets or sets the height, in points, of a Range. If all rows in the Range have the same height,
returns the height. If rows in the Range have different heights, returns None.
row_height must be in the range: 0 <= row_height <= 409.5
Note: If the Range is outside the used range of the Worksheet, and rows in the Range have
different heights, returns the height of the first row.
Returns
Return type float
New in version 0.4.0.
rows
Returns a RangeRows object that represents the rows in the specified range.
New in version 0.9.0.
select()
Selects the range. Select only works on the active book.
New in version 0.9.0.
shape
Tuple of Range dimensions.
New in version 0.3.0.
sheet
Returns the Sheet object to which the Range belongs.
New in version 0.9.0.
size
Number of elements in the Range.
New in version 0.3.0.
top
Returns the distance, in points, from the top edge of row 1 to the top edge of the range. Read-
only.
Returns
Return type float
New in version 0.6.0.
value
Gets and sets the values for the given Range.
Returns object
Return type returned object depends on the converter being used, see xlwings.
Range.options()
width
Returns the width, in points, of a Range. Read-only.
Returns
Return type float
New in version 0.4.0.
19.2.8 RangeRows
class xlwings.RangeRows(rng)
Represents the rows of a range. Do not construct this class directly, use Range.rows instead.
Example
import xlwings as xw
rng = xw.Range('A1:C4')
rng.rows[0].value = 'a'
for r in rng.rows:
print(r.address)
autofit()
Autofits the height of the rows.
count
Returns the number of rows.
New in version 0.9.0.
19.2.9 RangeColumns
class xlwings.RangeColumns(rng)
Represents the columns of a range. Do not construct this class directly, use Range.columns in-
stead.
Example
import xlwings as xw
rng = xw.Range('A1:C4')
rng.columns[0].value = 'a'
for c in rng.columns:
print(c.address)
autofit()
Autofits the width of the columns.
count
Returns the number of columns.
New in version 0.9.0.
19.2.10 Shapes
class xlwings.main.Shapes(impl)
A collection of all shape objects on the specified sheet:
api
Returns the native object (pywin32 or appscript obj) of the engine being used.
count
Returns the number of objects in the collection.
19.2.11 Shape
19.2.12 Charts
class xlwings.main.Charts(impl)
A collection of all chart objects on the specified sheet:
Examples
api
Returns the native object (pywin32 or appscript obj) of the engine being used.
count
Returns the number of objects in the collection.
19.2.13 Chart
api
Returns the native object (pywin32 or appscript obj) of the engine being used.
New in version 0.9.0.
chart_type
Returns and sets the chart type of the chart.
New in version 0.1.1.
delete()
Deletes the chart.
height
Returns or sets the number of points that represent the height of the chart.
left
Returns or sets the number of points that represent the horizontal position of the chart.
name
Returns or sets the name of the chart.
parent
Returns the parent of the chart.
New in version 0.9.0.
set_source_data(source)
Sets the source data range for the chart.
Parameters source (Range) – Range object, e.g. xw.books['Book1'].
sheets[0].range('A1')
top
Returns or sets the number of points that represent the vertical position of the chart.
width
Returns or sets the number of points that represent the width of the chart.
19.2.14 Pictures
class xlwings.main.Pictures(impl)
A collection of all picture objects on the specified sheet:
Examples
1. Picture
2. Matplotlib
api
Returns the native object (pywin32 or appscript obj) of the engine being used.
count
Returns the number of objects in the collection.
19.2.15 Picture
class xlwings.Picture(impl=None)
The picture object is a member of the pictures collection:
19.2.16 Names
class xlwings.main.Names(impl)
A collection of all name objects in the workbook:
19.2.17 Name
class xlwings.Name(impl)
The name object is a member of the names collection:
@xw.func
@xw.arg('x', np.array, ndim=2)
def add_one(x):
return x + 1
xlwings.ret(convert=None, **options)
Apply converters and options to return values, see also Range.options().
Examples
1. Suppress the index and header of a returned DataFrame:
import pandas as pd
@xw.func
@xw.ret(index=False, header=False)
def get_dataframe(n, m):
return pd.DataFrame(np.arange(n * m).reshape((n, m)))
2. Dynamic array:
expand='table' turns the UDF into a dynamic array. Currently you must not use volatile func-
tions as arguments of a dynamic array, e.g. you cannot use =TODAY() as part of a dynamic array.
Also note that a dynamic array needs an empty row and column at the bottom and to the right and will
overwrite existing data without warning.
Unlike standard Excel arrays, dynamic arrays are being used from a single cell like a standard function
and auto-expand depending on the dimensions of the returned array:
import xlwings as xw
import numpy as np
@xw.func
@xw.ret(expand='table')
(continues on next page)
License
97
xlwings - Make Excel Fly!, Release dev
A B
activate() (xlwings.App method), 69 Book (class in xlwings), 72
activate() (xlwings.Book method), 72 book (xlwings.Sheet attribute), 76
activate() (xlwings.Shape method), 87 Books (class in xlwings.main), 71
activate() (xlwings.Sheet method), 75 books (xlwings.App attribute), 69
active (xlwings.main.Apps attribute), 68
active (xlwings.main.Books attribute), 71 C
active (xlwings.main.Sheets attribute), 75 calculate() (xlwings.App method), 69
add() (xlwings.main.Apps method), 68 calculation (xlwings.App attribute), 69
add() (xlwings.main.Books method), 71 caller() (xlwings.Book class method), 72
add() (xlwings.main.Charts method), 88 cells (xlwings.Sheet attribute), 76
add() (xlwings.main.Names method), 92 Chart (class in xlwings), 89
add() (xlwings.main.Pictures method), 90 chart_type (xlwings.Chart attribute), 89
add() (xlwings.main.Sheets method), 75 Charts (class in xlwings.main), 88
add_hyperlink() (xlwings.Range method), 78 charts (xlwings.Sheet attribute), 76
address (xlwings.Range attribute), 78 clear() (xlwings.Range method), 78
api (xlwings.App attribute), 69 clear() (xlwings.Sheet method), 76
api (xlwings.Book attribute), 72 clear_contents() (xlwings.Range method), 78
api (xlwings.Chart attribute), 89 clear_contents() (xlwings.Sheet method), 76
api (xlwings.main.Charts attribute), 88 close() (xlwings.Book method), 73
api (xlwings.main.Names attribute), 92 color (xlwings.Range attribute), 78
api (xlwings.main.Pictures attribute), 91 column (xlwings.Range attribute), 79
api (xlwings.main.Shapes attribute), 86 column_width (xlwings.Range attribute), 79
api (xlwings.Name attribute), 93 columns (xlwings.Range attribute), 79
api (xlwings.Picture attribute), 91 count (xlwings.main.Apps attribute), 68
api (xlwings.Range attribute), 78 count (xlwings.main.Charts attribute), 88
api (xlwings.Sheet attribute), 76 count (xlwings.main.Names attribute), 92
App (class in xlwings), 68 count (xlwings.main.Pictures attribute), 91
app (xlwings.Book attribute), 72 count (xlwings.main.Shapes attribute), 87
Apps (class in xlwings.main), 68 count (xlwings.Range attribute), 79
autofit() (xlwings.Range method), 78 count (xlwings.RangeColumns attribute), 86
autofit() (xlwings.RangeColumns method), 86 count (xlwings.RangeRows attribute), 86
autofit() (xlwings.RangeRows method), 85 current_region (xlwings.Range attribute), 79
autofit() (xlwings.Sheet method), 76
99
xlwings - Make Excel Fly!, Release dev
G P
get_address() (xlwings.Range method), 81 parent (xlwings.Chart attribute), 89
parent (xlwings.Picture attribute), 91
H parent (xlwings.Shape attribute), 87
height (xlwings.Chart attribute), 89 Picture (class in xlwings), 91
height (xlwings.Picture attribute), 91 Pictures (class in xlwings.main), 89
height (xlwings.Range attribute), 81 pictures (xlwings.Sheet attribute), 77
height (xlwings.Shape attribute), 87 pid (xlwings.App attribute), 70
hwnd (xlwings.App attribute), 69
hyperlink (xlwings.Range attribute), 81 Q
quit() (xlwings.App method), 70
I
index (xlwings.Sheet attribute), 76 R
Range (class in xlwings), 77
K range() (xlwings.App method), 70
kill() (xlwings.App method), 70 range() (xlwings.Sheet method), 77
RangeColumns (class in xlwings), 86
L RangeRows (class in xlwings), 85
last_cell (xlwings.Range attribute), 82 raw_value (xlwings.Range attribute), 83
left (xlwings.Chart attribute), 89 refers_to (xlwings.Name attribute), 93
left (xlwings.Picture attribute), 91 refers_to_range (xlwings.Name attribute), 93
left (xlwings.Range attribute), 82 resize() (xlwings.Range method), 83
left (xlwings.Shape attribute), 87 row (xlwings.Range attribute), 84
row_height (xlwings.Range attribute), 84
M rows (xlwings.Range attribute), 84
macro() (xlwings.App method), 70
macro() (xlwings.Book method), 73 S
save() (xlwings.Book method), 74
N screen_updating (xlwings.App attribute), 70
Name (class in xlwings), 93 select() (xlwings.Range method), 84
name (xlwings.Book attribute), 73 select() (xlwings.Sheet method), 77
100 Index
xlwings - Make Excel Fly!, Release dev
T
top (xlwings.Chart attribute), 89
top (xlwings.Picture attribute), 91
top (xlwings.Range attribute), 85
top (xlwings.Shape attribute), 87
type (xlwings.Shape attribute), 87
U
update() (xlwings.Picture method), 92
V
value (xlwings.Range attribute), 85
version (xlwings.App attribute), 71
view() (in module xlwings), 67
visible (xlwings.App attribute), 71
W
width (xlwings.Chart attribute), 89
width (xlwings.Picture attribute), 92
width (xlwings.Range attribute), 85
width (xlwings.Shape attribute), 88
X
xlwings (module), 67
xlwings.arg() (in module xlwings), 94
xlwings.func() (in module xlwings), 93
xlwings.ret() (in module xlwings), 94
xlwings.sub() (in module xlwings), 94
Index 101