Home > Software engineering >  Print function wont return data from xlsx sheet in Python with openpyxl
Print function wont return data from xlsx sheet in Python with openpyxl

Time:05-18

I'm looking import a row of strings from an xlsx document and iterate them into Python to be used as a variable elsewhere. For now I'm trying to simply have them printed out as proof the code works.

For some reason, the code runs without any errors but does not print anything out.

From what I've been reading in openpyxl's documentation this should be working fine, I can't figure out what the problem is.

I'm assuming it's something to do with my if statement but as far as I can tell everything checks out.

Perhaps there's an issue identifying the column?

For clarification, the column I'm trying to access is 'B'. The first cell of B is the header and cells 2-max sheet is the data.

My code:

from openpyxl import load_workbook

path = "/Users/xxx/Desktop/alpha list test.xlsx"
book = load_workbook(path)
sheet = book['Sheet1']

column_name = 'username'
for column_cell in sheet.iter_cols(1, sheet.max_column):
    if column_cell[0] == column_name:
        B = 0
        for data in column_cell[1:]:
            htag = data.value
            print(htag)

Which results in:

Process finished with exit code 0

The /xxx/ in the path is to hide personal information.

CodePudding user response:

column_cell is a tuple of objects. So column_cell[0] is the first tuple but the object is not going to equal a string value

if column_cell[0] == column_name:

try using the value attribute, otherwise it will not match your header and never continue to the print part of the code.

if column_cell[0].value == column_name:
  • Related