Python中openpyxl使用iter_rows()的方法

1,589次阅读
没有评论
Python中openpyxl使用iter_rows()的方法

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

当我们使用以下代码:

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

</pre>
然后会出现,此代码返回:

type object ‘Worksheet’ has no attribute ‘iter_rows’
<pre class="brush:js;toolbar:false">

怎么会出现这种情况?

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

>>> for row in ws.iter_rows(‘A1:C2’): …        for cell in row: …            print cell

</pre>
要么

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2): …    for cell in row: …        print(cell)
<pre class="brush:js;toolbar:false">

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

op.worksheet.Worksheet.iter_rows()  # wrong

</pre>
对于旧版本的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’) …
<pre class="brush:js;toolbar:false">

还没有学会的小伙伴不要着急,结合之前学习再重新看一遍今天的示例。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-08发表,共计1024字。
新手QQ群:570568346,欢迎进群讨论 Python51学习