Python openpyxl read until empty cell

随声附和 提交于 2019-12-07 07:59:28

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)

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.

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