Search code examples
pythonexcelpython-3.xopenpyxlattributeerror

Python read 1 column of Excel file


I'm trying to use openpyxl to read 1 column out of a Excel-file until it hits an empty cell, then it needs to stop. But i don't get it working. This is my code so far:

import openpyxl
import os

def main():
    filePath = os.getcwd() + "\file.xlsx"

    wb = openpyxl.load_workbook(filename=filePath, read_only=True)
    sheet = wb["Sheet1"]


    for row in range(sheet.max_row):
        if(sheet.cell(row+1,1).value == None):
            break
        print(sheet.cell(row+1,1).value)


if __name__ == "__main__":
    main()

But this results in the following error:

Traceback (most recent call last):
File "someProgram.py", line 27, in main() File "someProgram.py", line 15, in main
if(sheet.cell(row+1,1).value == None):
File "C:\Python34\lib\openpyxl\worksheet\worksheet.py", line 349,
in cell coordinate = coordinate.upper().replace('$', '')
AttributeError: 'int' object has no attribute 'upper'


Solution

  • The problem is with this line:

    if(sheet.cell(row+1,1).value == None):
    

    sheet.cell is expecting to have a str cell name such as A1 and not of type int for one parameter function.

    You need to specify the row and column keys such as:

    sheet.cell(row=row+1, column=1).value
    

    if you specify an int type row and column variables