KnakworstKoning
KnakworstKoning

Reputation: 371

Python openpyxl read until empty cell

I'm trying to read one column out of my Excel-file until it hits an empty cell, then it needs to stop reading. My code so far:

import openpyxl
import os

def main():
    filepath = os.getcwd() + "\test.xlsx"

    wb = openpyxl.load_workbook(filename=filepath, read_only=True)
    ws = wb['Tab2']

    for i in range(2, 1000):
        cellValue = ws.cell(row=i, column=1).Value
        if cellValue != None:
            print(str(i) + " - " + str(cellValue))
        else:
            break;

if __name__ == "__main__":
    main() 

By running this i get the following error when it hits an empty cell. Does anybody know how i can prevent this from happening.

Traceback (most recent call last):
  File "testFile.py" in <module>
      main()
      cellValue = sheet.cell(row=i, column=1).value
  File "C:\Python34\lib\openpyxl\worksheet\worksheet.py", line 353, in cell
      cell = self._get_cell(row, column)
  File "C:\Python34\lib\openpyxl\worksheet\read_only.py", line 171, in _get_cell
      cell = tuple(self.get_squared_range(column, row, column, row))[0]
IndexError: tuple index out of range

Upvotes: 2

Views: 15291

Answers (2)

Charlie Clark
Charlie Clark

Reputation: 19497

This illustrates one of the reasons why I don't encourage the use of ws.cell() for reading worksheet. You're much better off with the higher level API ws.iter_rows() (ws.iter_cols() is not possible in read-only mode for performance reasons.

for row in ws.iter_rows(min_col=1, max_col=1):
    if row[0].value is None:
        break
    print("{0}-{1}".format(row[0].row, row[0].value))

iter_rows should guarantee there is always a cell in reach row.

Upvotes: 2

HaR
HaR

Reputation: 1067

Try with max_row to get the maximum number of rows.

from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook('exc_file.xlsx')
ws1 = wb['Sheet1']
for row in range(1,ws1.max_row):
    if(ws1.cell(row,1).value is not None):
            print(ws1.cell(row,1).value)

OR if you want to stop reading when it reaches an empty value you can simply:

from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook('exc_file.xlsx')
ws1 = wb['Sheet1']
for row in range(1,ws1.max_row):
    if(ws1.cell(row,1).value is None):
        break
    print(ws1.cell(row,1).value)

Upvotes: 6

Related Questions