lasse
lasse

Reputation: 21

openpyxl - How to use column number instead of letter?

I was looking for a way to read a single column from an xlsx using openpyxl and found something on this page (first answer): openpyxl - read only one column from excel file in python?

But there's one problem with this code: You cannot enter columns right to 'Z', as the program thinks that (e.g. instead of column 'AD') the two columns 'A' and 'D' are meant. Does anybody have an idea on how to fix this issue? I appreciate every answer (:

for row in range(4,sheet.max_row+1):  
    for column in 'E':
        cell_name = '{}{}'.format(column, row)
        val = sheet[cell_name].value

Upvotes: 1

Views: 1820

Answers (1)

r.ook
r.ook

Reputation: 13888

When you do for column in 'AD': it's really splitting 'AD' into 'A' and 'D' and column will represent each of these in the iterations.

If you wanted to do the column names you should have done:

for column in ('A', 'E', 'AD', 'AZ', 'CC', ...): # etc for all your desired columns
        cell_name = '{}{}'.format(column, row)
        val = sheet[cell_name].value

If you just wanted numerical reference, use sheet.cell(row, col).value

Upvotes: 4

Related Questions