Search code examples
pythonexcelpywin32

Reading and analyzing data from Excel sheets using pywin32


I've seen plenty of examples on how to write to excel, and my program requires reading from existing data. I need to read through a column and pick out numbers from it (the column is empty cells with numbers at arbitrary intervals), and then break out when I reach the end of the data. The code I have now is below, where xlsht is the sheet name, x and y are the cell indices, and address is the list all the numbers are going.

while y < xlsht.UsedRange:
    if str(xlsht.Cells(x,y).Value).isdigit:
        address.append(xlsht.Cells(x,y).Value)
        y += 1
        continue
    else:
        y += 1
return address

As it stands now, it crashes at line 2. I tried using

if xlsht.Cells(x,y).Value not None:

but that didn't work. I dont know how else to do this. Also, I wanted to verify that using

xlsht.UsedRange 

is the correct way of detecting the last row of the sheet.


Solution

  • The error message doesn't give any useful clues what the problem might be.

    Soltuion: Poor man's debugger. Print all and any variables so you can see what is going on:

    print 'xlsht=',xlsht
    print 'x=',x
    print 'usedRange=',xlsht.UsedRange
    while y < xlsht.UsedRange:
        print 'y=',y
        print 'cell=',xlsht.Cells(x,y)
        print 'value=',xlsht.Cells(x,y).Value
        if str(xlsht.Cells(x,y).Value).isdigit:
            address.append(xlsht.Cells(x,y).Value)
            y += 1
            continue
        else:
            y += 1
    return address
    

    You get the idea. If you're using Python 3.x, you'll need print('x=',repr(x))