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

use*_*243 11 python excel openpyxl canopy

我正在使用openpyxlPython(Canopy)来使用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>
Run Code Online (Sandbox Code Playgroud)

我们如何openpyxl.worksheet.Worksheet.iter_rows()在python中导入方法?我用过这段代码:

import openpyxl as op
ms = op.load_workbook('mtest.xlsx')

ws = ms.active

op.worksheet.Worksheet.iter_rows()
Run Code Online (Sandbox Code Playgroud)

此代码返回:

type object 'Worksheet' has no attribute 'iter_rows' 
Run Code Online (Sandbox Code Playgroud)

问题是什么?

DNA*_*DNA 15

教程所示,您需要iter_rows在工作表的实例上调用该方法,例如:

>>> for row in ws.iter_rows('A1:C2'):
...        for cell in row:
...            print cell
Run Code Online (Sandbox Code Playgroud)

要么

>>> 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>
Run Code Online (Sandbox Code Playgroud)

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

op.worksheet.Worksheet.iter_rows()  # wrong
Run Code Online (Sandbox Code Playgroud)

另请参阅另一个答案中的此示例.

对于旧版本的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')
...
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,对于 ws.iter_rows('A1:C2'): 中的行:没有工作,但对于 ws.iter_rows(min_row=1, max_col=3, max_row=2) 中的行:做了。第一个语法给出了一个 TypeError: 'str' object cannot be interpret as an integer。 (4认同)
  • 您不需要在最近的版本中启用迭代器;标准工作表也有 `iter_rows()` 方法。 (2认同)