xlwings
xlwings is a BSD-licensed Python library that simplifies interaction with Microsoft Excel, enabling automation and powerful data manipulation. It allows users to call Python from Excel and vice versa, supporting scripting, macros, and User Defined Functions (UDFs) on Windows and macOS. The library is actively maintained with frequent releases, currently at version 0.35.1.
Warnings
- breaking The `@sub` decorator used for exposing Python functions to Excel VBA has been renamed to `@script` in v0.35.0 to align with xlwings Lite. `@sub` is now deprecated.
- breaking The `range.insert()` method now explicitly requires the `shift` argument. The previous default behavior of letting Excel guess the shift direction is no longer supported.
- gotcha xlwings (Open Source) fundamentally requires a local installation of Microsoft Excel on Windows or macOS to function. It does not work standalone for file manipulation on Linux without additional xlwings PRO or Server components.
- gotcha When calling Python functions from Excel VBA via `RunPython`, placing `xw.Book.caller()` outside the called function (e.g., as a global variable) can prevent Excel from shutting down properly, leading to 'zombie' Excel processes, especially when `Use UDF Server = True` is active.
- gotcha A bug existed where xlwings conflicted with Microsoft's new Python in Excel feature (introduced by `=PY()`). This required users to re-import User-defined functions (UDFs) after upgrading to resolve conflicts.
- gotcha The xlwings Excel add-in's version must match the installed xlwings Python package version. Mismatches can lead to unexpected behavior or errors.
Install
-
pip install xlwings -
conda install -c conda-forge xlwings
Imports
- xlwings
import xlwings as xw
Quickstart
import xlwings as xw
# Start an Excel app (visible=False runs it in the background)
# xlwings (Open Source) requires Excel to be installed on the machine.
try:
app = xw.App(visible=False)
# Open an existing workbook or create a new one
# wb = app.books.open("path/to/my_workbook.xlsx")
wb = app.books.add() # Create a new, empty workbook
sheet = wb.sheets
# Write a value to cell A1
sheet.range('A1').value = 'Hello from xlwings!'
# Read a value from cell A1
cell_value = sheet.range('A1').value
print(f"Value in A1: {cell_value}")
# Write a 2D list to a range (will expand automatically)
sheet.range('A3').value = [['Header1', 'Header2'],,]
# Save the workbook (optional)
# wb.save("my_output.xlsx")
# print("Workbook saved as my_output.xlsx")
finally:
# Ensure Excel app is quit even if errors occur
if 'app' in locals() and app.alive:
wb.close() # Close the workbook (without saving if not explicitly saved)
app.quit()
print("Excel application quit.")