语法概述¶
xlwings 的对象模型与 VBA 使用的非常相似。
下面的所有代码示例都依赖于以下导入:
>>> import xlwings as xw
活动对象¶
# Active app (i.e. Excel instance)
>>> app = xw.apps.active
# Active book
>>> wb = xw.books.active # in active app
>>> wb = app.books.active # in specific app
# Active sheet
>>> sheet = xw.sheets.active # in active book
>>> sheet = wb.sheets.active # in specific book
可以通过 A1 表示法、Excel 的基于 1 的索引元组或命名区域来实例化 Range。
import xlwings as xw
sheet1 = xw.Book("MyBook.xlsx").sheets[0]
sheet1.range("A1")
sheet1.range("A1:C3")
sheet1.range((1,1))
sheet1.range((1,1), (3,3))
sheet1.range("NamedRange")
# Or using index/slice notation
sheet1["A1"]
sheet1["A1:C3"]
sheet1[0, 0]
sheet1[0:4, 0:4]
sheet1["NamedRange"]
完全限定¶
圆括号遵循 Excel 的行为(即基于 1 的索引),而方括号使用 Python 的基于 0 的索引/切片。例如,以下表达式都引用相同的范围:
xw.apps[763].books[0].sheets[0].range('A1')
xw.apps(10559).books(1).sheets(1).range('A1')
xw.apps[763].books['Book1'].sheets['Sheet1'].range('A1')
xw.apps(10559).books('Book1').sheets('Sheet1').range('A1')
注意,应用程序键对你来说是不同的,因为它们是进程 ID (PID)。你可以通过以下方式获取你的 PID 列表xw.apps.keys()
.
应用上下文管理器¶
如果你想通过打开一个新的 Excel 实例App()
,通常应该使用App
作为上下文管理器,因为这将确保 Excel 实例被正确关闭并清理:
with xw.App() as app:
book = app.books['Book1']
区域索引/切片¶
区域对象支持索引和切片,以下是一些例子:
>>> myrange = xw.Book().sheets[0].range('A1:D5')
>>> myrange[0, 0]
<Range [Workbook1]Sheet1!$A$1>
>>> myrange[1]
<Range [Workbook1]Sheet1!$B$1>
>>> myrange[:, 3:]
<Range [Workbook1]Sheet1!$D$1:$D$5>
>>> myrange[1:3, 1:3]
<Range [Workbook1]Sheet1!$B$2:$C$3>
区域快捷方式¶
工作表对象通过在工作表对象上使用索引/切片表示法为区域对象提供快捷方式。这取决于你传递的是字符串还是索引/切片:sheet.range
或sheet.cells
depending on whether you pass a string or indices/slices:
>>> sheet = xw.Book().sheets['Sheet1']
>>> sheet['A1']
<Range [Book1]Sheet1!$A$1>
>>> sheet['A1:B5']
<Range [Book1]Sheet1!$A$1:$B$5>
>>> sheet[0, 1]
<Range [Book1]Sheet1!$B$1>
>>> sheet[:10, :10]
<Range [Book1]Sheet1!$A$1:$J$10>
对象层次结构¶
以下显示了对象层次结构的一个示例,即如何从应用程序到区域对象再返回的整个过程:
>>> myrange = xw.apps[10559].books[0].sheets[0].range('A1')
>>> myrange.sheet.book.app
<Excel App 10559>