1

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
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
lasse
  • 21
  • 4
  • 1
    Use a tuple, list or non-string sequence, i.e., `for column in ['E', 'AD', 'Z']:` etc.? – David Zemens Feb 28 '19 at 19:47
  • That previous answer is taking advantage of the fact that a string is a *sequence* of characters, but obviously if you need an identifier that is 2 characters such as "AD", you can't exploit that, and you need to slightly modify the approach. – David Zemens Feb 28 '19 at 19:48
  • Use `sheet['E']`. Covered in the docs. – Charlie Clark Mar 01 '19 at 08:37

1 Answers1

2

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

r.ook
  • 13,466
  • 2
  • 22
  • 39