连接到Excel工作簿¶
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 |
|
---|---|---|
新建工作簿 |
|
|
未保存的工作簿 |
|
|
有全路径的工作簿 |
|
|
备注
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)¶
To reference the calling book when using RunPython
in VBA, use xw.Book.caller()
, see
用”RunPython”调用Python.
Check out the section about 调试 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.
用户定义函数(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.