Home » excel » python – Parsing a column using openpyxl

python – Parsing a column using openpyxl

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have the following algorithm to parse a column for integer values:

def getddr(ws):
address = []
col_name = 'C'
start_row = 4
end_row = ws.get_highest_row()+1

range_expr = "{col}{start_row}:{col}{end_row}".format(col=col_name, start_row=start_row, end_row=end_row)

for row in ws.iter_rows(range_string=range_expr):
    print row
    raw_input("enter to continue")
    cell = row[0]
    if str(cell.value).isdigit:
        address.append(cell.value)
    else:
        continue

return address

This crashes at cell = row[0] saying “IndexError: tuple index out of range”, and i dont know what this means. I tried printing out row to see what it contained, but all it gives me is an empty set of parentheses. Anyone know what I’m missing?

How to&Answers:

That is not so easy to say what is the problem you have, because there are no input data that you are trying to process.

But I can explain what is the reason of the error you’ve get, and in which direction you must go. The list row contains 0 elements (row = []), because of that you can not say row[0] — there are no row[0]. The first thing you must change is check, how long is your list, and when if it is long enough make other things:

for row in ws.iter_rows(range_string=range_expr):
    print row
    raw_input("enter to continue")
    if len(row) > 0:
      cell = row[0]
      if str(cell.value).isdigit:
        address.append(cell.value)
      else:
        continue

That is the first step that you must do anyway.