pythonexcelcomcomtypes

How to get value of Excel cell from COM client


Right now I am failing to retrieve values from Excel cells read by COM and Python using the following code:

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)

I always get

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

printed on the screen instead of the value of the cell.

What am I doing wrong?


Solution

  • According to 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. So this should work:

    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)
    

    Not on a Windows computer though, so can't test this ATM.