我们如何在Python openpyxl包中使用iter_rows()? [英] How we can use iter_rows() in Python openpyxl package?

查看:5948
本文介绍了我们如何在Python openpyxl包中使用iter_rows()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Python(Canopy)中的 openpyxl 包使用Excel文件。我们在此链接中有本教程: LINK

I'm using openpyxl package in Python(Canopy) to use excel files. We have this tutorial in this link : LINK

you can also use the openpyxl.worksheet.Worksheet.iter_rows() method:

>>> tuple(ws.iter_rows('A1:C2'))
((<Cell Sheet1.A1>, <Cell Sheet1.B1>, <Cell Sheet1.C1>),
 (<Cell Sheet1.A2>, <Cell Sheet1.B2>, <Cell Sheet1.C2>))

>>> for row in ws.iter_rows('A1:C2'):
...        for cell in row:
...            print cell
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>

我们如何导入 openpyxl.worksheet.Worksheet.iter_rows() code> python中的方法?我使用这个代码:

How we can import openpyxl.worksheet.Worksheet.iter_rows() method in python? I used this code:

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 方法,例如:

As shown in the tutorial, you need to call the iter_rows method on an instance of a worksheet, for example:

>>> 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)
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>

正如您的错误消息所述,您在 Worksheet 类型,将不起作用;

As your error message states, you are calling it on the Worksheet type, which won't work; it needs to be called on an object:

op.worksheet.Worksheet.iter_rows()  # wrong

另请参见这个例子在另一个答案。

See also this example in another answer.

对于旧版本的openpyxl,您可能需要确保在加载工作簿时启用迭代器 - 请参阅这个线程

For older versions of openpyxl, you may need to ensure that you enable iterators when loading your workbook - see this thread. This isn't required for more recent versions.

这是一个完整的例子,我刚刚在Python REPL中测试(使用openpyxl 1.8.3):

Here's a complete example which I just tested in the Python REPL (with 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 openpyxl包中使用iter_rows()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆