How it Works

PyXLL is an Excel addin that enables functions written in Python to be called in Excel.

Python functions can either be exposed as Excel user defined functions that can be called from worksheets, as custom menu items, or as macros.

To use PyXLL you must have Python installed, and it must be the version corresponding to the version of PyXLL you have downloaded. You must also have the standard python modules included in your system’s PYTHONPATH, which is usually done for you by the Python installer.

User defined functions

User defined functions added via PyXLL are identical in appearance to any other functions available in excel, the only difference is they are significantly easier and faster to write.

Here’s a simple example of a user defined worksheet function to get started with:

from pyxll import xl_func
@xl_func("string name: string")
def hello(name):
    """returns a familiar greeting"""
    return "Hello, %s" % name

The decorator xl_func tells PyXLL what arguments the function takes and (optionally) the return type so it can register it correctly in Excel. The argument text you see in Excel is taken from this signature, and the function help is taken from the function’s docstring.

And that’s it. There is no more code to write to get that function in Excel. There’s nothing to compile; you don’t even need to restart Excel to see it!

To see this new function in Excel, the PyXLL addin is loaded via the addins menu in Excel in the same way as any other addin.

The PyXLL addin automatically picks up any imported functions with the xl_func decorator. By default the functions are added to the PyXLL category in Excel, but that can be altered on a per function basis using the optional argument category to xl_func.

Here’s how this python function looks in Excel:

Illustration: Insert function in Excel using PyXLL Illustration: Function arguments using PyXLL Illustration: The Excel worksheet using the Python function

Adding custom menus is just as easy. You use the xl_menu decorator to expose a python function as a menu callback. PyXLL creates the menu item for you, and when it’s selected your python function is called. That python function can call back into Excel using win32com to make changes to the current sheet or workbook.

Different menus can be created and you can also create submenus. The order in which the items appear is controlled by optional keyword arguments to the xl_menu decorator.

Here’s a very simple example that uses the win32api module to pop up a message box when the user selects the menu item:

from pyxll import xl_menu
import win32api

def on_hello():
    win32api.MessageBox(0, "Hello!", "Hello!")

Here’s how that menu item looks in Excel:

Illustration: PyXLL menu item in Excel

For more information about what’s possible with PyXLL continue to the features page.