【问题标题】:How we can use iter_rows() in Python openpyxl package?我们如何在 Python openpyxl 包中使用 iter_rows()?
【发布时间】:2015-04-22 08:43:16
【问题描述】:

我正在使用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' 

有什么问题?

【问题讨论】:

    标签: python excel canopy openpyxl


    【解决方案1】:

    tutorial所示,您需要在工作表的实例上调用iter_rows方法,例如(对于openpyxl 2.5.14或更早版本):

    >>> 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 type 上调用它,这是行不通的;它需要在 object 上调用:

    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')
    ...
    

    【讨论】:

    • 您不需要在最近的版本中启用迭代器;标准工作表也有iter_rows() 方法。
    • 谢谢 - 我似乎有一个相当旧的版本(1.8.3;最新的是 2.2.1) - 会稍微编辑答案。
    • 升级通常是值得的。将很快发布 2.2.2 错误版本,但即便如此 2.2 比 1.8 更可靠、更快
    • 对我来说,对于 ws.iter_rows('A1:C2') 中的行:没有用,但对于 ws.iter_rows(min_row=1, max_col=3, max_row=2) 中的行:做过。第一种语法给出了 TypeError: 'str' 对象不能被解释为整数。
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2020-08-09
    • 2022-09-25
    • 1970-01-01
    • 2020-11-14
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多