Python openpyxl read until empty cell

限于喜欢 提交于 2020-01-14 03:00:09

问题


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

回答1:


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)



回答2:


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 cell[0].value is None:
         break
    print("{0}-{1}".format(cell.row, cell.value)

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



来源:https://stackoverflow.com/questions/49365992/python-openpyxl-read-until-empty-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!