当前位置: 首页 > 图灵资讯 > 行业资讯> 关于Python中openpyxl使用iter_rows()的方法

关于Python中openpyxl使用iter_rows()的方法

来源:图灵python
时间: 2025-01-02 17:15:19

之前已经对iter函数的用法有过讲解,记忆遗忘的小伙伴可以重新回顾一遍。今天就iter函数的拓展,讲讲openpyxl中导入iter_rows()的方法。

当我们使用以下代码:

import openpyxl as op ms = op.load_workbook('mtest.xlsx') ws = ms.active op.worksheet.Worksheet.iter_rows()

然后会出现,此代码返回:

type object 'Worksheet' has no attribute 'iter_rows'

怎么会出现这种情况?

这说明,您需要在工作表的实例上调用iter_rows方法,例如:

>>> for row in ws.iter_rows('A1:C2'): ... for cell in row: ... print cell

要么

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2): ... for cell in row: ... print(cell)

正如您的错误消息所述,您在Worksheet类型上调用它,这将无效;它需要在一个对象上调用:

op.worksheet.Worksheet.iter_rows() # wrong

对于旧版本的openpyxl,您可能需要确保在加载工作簿时启用迭代器 –对于更新版本,这不是必需的。

以下是一个完整的例子在Python REPL中测试过(使用openpyxl 1.8.3):

>>> import openpyxl as op >>> wb = op.load_workbook('/tmp/test.xlsx', use_iterators=True) >>> ws = wb.active >>> for row in ws.iter_rows(): ... for cell in row: ... print cell ... RawCell(row=1, column='A', coordinate='A1', internal_value=1.0, data_type='n', style_id='0', number_format='general') RawCell(row=1, column='B', coordinate='B1', internal_value=10.0, data_type='n', style_id='0', number_format='general') ...

还没有学会的小伙伴不要着急,结合之前学习再重新看一遍今天的示例,Python基础知识回顾:iter函数。