我正在使用 pywin32 并尝试获取特定单元格的 R1C1 地址。在 VBA 中,您可以使用
Range.Address(ReferenceStyle:=xlR1C1)
.
但是,在pywin32中,使用
Range.Address
似乎不是允许参数的方法,而是一个只返回A1风格字符串的属性。
from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
wb = xl.Workbooks.Open('my_workbook.xlsx')
sht = wb.sheets['Sheet1']
c = sht.Range("A1")
c.Address
# returns "$A$1"
c.Address(ReferenceStyle=-4150)
# TypeError: 'str' object is not callable
@lifeisstillgood 在这个SO 问题中的回答 给出了指导。
win32com
通过安静地生成 Get 和/或 Set 方法来解决 Property
调用的问题(即实际上是 Methods
伪装)。
具体方法将取决于 Excel 对象的创建方式。
Dispatch()
和后期绑定。在这里你似乎需要将默认参数添加到调用中,顺序为here. xl=win32com.client.Dispatch('Excel.Application')
...
c.GetAddress(True,True,-4150)
EnsureDispatch()
和早期绑定。这里 win32com
生成 Python 包装器,它允许命名参数,并且还生成 Excel 常量。 xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
...
c.GetAddress(ReferenceStyle=win32com.client.constants.xlR1C1)
如果你查看
Range.py
包装器,这个函数已经生成:
# The method GetAddress is actually a property, but must be used as a method to correctly pass the arguments
def GetAddress(self, RowAbsolute=defaultNamedNotOptArg, ColumnAbsolute=defaultNamedNotOptArg, ReferenceStyle=1, External=defaultNamedOptArg, RelativeTo=defaultNamedOptArg):
# Result is a Unicode object
return self._oleobj_.InvokeTypes(236, LCID, 2, (8, 0), ((12, 17), (12, 17), (3, 49), (12, 17), (12, 17)),RowAbsolute
, ColumnAbsolute, ReferenceStyle, External, RelativeTo)