连接到Excel工作簿

不用工作簿对象,也能在一个活动工作表中读写数据:

>>> import xlwings as xw
>>> xw.Range('A1').value = 'something'

Python到Excel

xw.Book 提供了连接到工作簿的最简单的方法: 它在所有的app实例中查找指定的工作簿,如果同一个工作簿在多个app实例中存在,就会返回一个错误信息。 连接活动app实例中的工作簿用 xw.books ,连接指定app实例中的工作簿用:

>>> app = xw.App()  # or something like xw.apps[10559] for existing apps, get the available PIDs via xw.apps.keys()
>>> app.books['Book1']

Note that you usually should use App as a context manager as this will make sure that the Excel instance is closed and cleaned up again properly:

with xw.App() as app:
    book = app.books['Book1']

xw.Book

xw.books

新建工作簿

xw.Book()

xw.books.add()

未保存的工作簿

xw.Book('Book1')

xw.books['Book1']

有全路径的工作簿

xw.Book(r'C:/path/to/file.xlsx')

xw.books.open(r'C:/path/to/file.xlsx')

注解

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.

Excel到Python(RunPython)

在VBA中用 RunPython 引用工作簿时,可以使用 xw.Book.caller() ,参考 用”RunPython”调用Python 。查阅 调试 了解如何从Pyhton和Excel调用脚本并避免一直在 xw.Book.caller() 和上文提及的方法间不停切换。

用户定义函数(UDFs)

Unlike RunPython, UDFs don’t need a call to xw.Book.caller(), see User Defined Functions (UDFs). You’ll usually use the caller argument which returns the xlwings range object from where you call the function.