如何从 COM 客户端获取 Excel 单元格的值

How to get value of Excel cell from COM client

现在我无法使用以下代码从 COM 和 Python 读取的 Excel 单元格中检索值:

from comtypes.client import CreateObject
filename=r'testrap.xlsx'
app = CreateObject("Excel.Application")
app.Visible = True
wb = app.Workbooks.Open(filename)
worksheet = wb.sheets(1)

for row in range(1,11):
    data = worksheet.Cells(row,1).Value
    print(data)

我总是

comtypes.client.lazybind.NamedProperty object at 0x....

打印在屏幕上而不是单元格的值。

我做错了什么?

根据the documentation for comtypes, properties with arguments are accessed using index notation. wb.Sheets[1] and worksheet.Cells[2] are properties with arguments and not methods. In addition, Value[3] is a property with an optional argument。所以这应该有效:

from comtypes.client import CreateObject
filename=r'testrap.xlsx'
app = CreateObject("Excel.Application")
app.Visible = True
wb = app.Workbooks.Open(filename)
worksheet = wb.Sheets[1]

for row in range(1,11):
    data = worksheet.Cells[row, 1].Value()
    print(data)

不过 Windows 计算机上没有,所以无法测试此 ATM。