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

标签 python excel canopy openpyxl

我在 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' 

问题是什么?

最佳答案

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 上调用它,这将不起作用;它需要在对象上调用:

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

关于python - 我们如何在 Python openpyxl 包中使用 iter_rows()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29792134/

相关文章:

vba - Excel VBA : setting font style and size while adding text to MS-Word

VBA方法 'range of object'_Worksheet在范围声明中使用的变量失败

python - 在 Linux 中创建安装程序包

excel - 更改工作表上所有图表中的系列名称

python - 如何列出忽略模块导入函数的 Python 模块的所有函数?

python-2.7 - 没有名为 os.path : wrong Python being called by bash 的模块

python - 在 MacOS 10.9.2 上从 Enthought Canopy 运行 winpdb

python - 让 PyC​​all 与 Julia 和 Enthought 的 Canopy 一起工作

python - 如何使用 DJango 在网络浏览器中显示 rsync --progress?

python - 如何在 Firefox 或 Chrome 中使用 Selenium webdriver 更改屏幕截图的目标目录