如何在Python openpyxl包中使用iter_rows()?

2024-04-25 12:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python(Canopy)中的openpyxl包来使用excel文件。我们在这个链接中有这个教程: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>

如何在python中导入openpyxl.worksheet.Worksheet.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' 

怎么了?


Tags: a2wsa1cellb2b1rowsc2
1条回答
网友
1楼 · 发布于 2024-04-25 12:37:16

tutorial所示,您需要调用工作表实例上的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)
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>

如错误消息所述,您是在Worksheet类型的上调用它,这将不起作用;它需要在对象上调用:

op.worksheet.Worksheet.iter_rows()  # wrong

另请参见另一个答案中的this example

对于旧版本的openpyxl,您可能需要确保在加载工作簿时启用迭代器-请参见this thread。对于较新版本,这不是必需的。

下面是一个完整的示例,我刚刚在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')
...

相关问题 更多 >