本文介绍了Python openpyxl读取直到空单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从Excel文件中读取一列,直到它碰到一个空单元格,然后它需要停止读取.到目前为止,我的代码:
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
推荐答案
尝试使用max_row获取最大行数.
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)
这篇关于Python openpyxl读取直到空单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!