與工作簿建立聯繫#
用 Python 操作 Excel#
建立與一個工作簿的聯繫最簡單的方式,是透過 xw.Book()
:該物件會根據使用者輸入的名稱搜尋並開啓特定的工作簿,若無指定名稱,便會建立一個新的工作簿並與之建立聯繫。 若使用當下有多個被開啓的工作簿,則可透過 xw.books
讀取被開啓工作簿的集合:
>>> 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 |
|
---|---|---|
新工作簿 |
|
|
尚未儲存的工作簿 |
|
|
根據路徑開啓的工作簿 |
|
|
備註
在 Windows 作業系統下指定檔案路徑時,爲了避免反斜線符號()被誤認成跳脫字元,你應該使用 Python 的原始字串,在字串的前面加上 r
,或是在字串内容所有的反斜線前面加上另一個反斜線,像是:C:\\path\\to\\file.xlsx
。
用 Excel 操作 Python (RunPython)#
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.
使用者自定函數(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.