我们如何在 Python openpyxl 包中使用 iter_rows()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29792134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How we can use iter_rows() in Python openpyxl package?
提问by Eghbal
I'm using openpyxl
package in Python(Canopy)
to use excel files. We have this tutorial in this link : LINK
我正在使用openpyxl
package inPython(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>
How we can import openpyxl.worksheet.Worksheet.iter_rows()
method in python? I used this code:
我们如何openpyxl.worksheet.Worksheet.iter_rows()
在python中导入方法?我使用了这个代码:
import openpyxl as op
ms = op.load_workbook('mtest.xlsx')
ws = ms.active
op.worksheet.Worksheet.iter_rows()
This code returns:
此代码返回:
type object 'Worksheet' has no attribute 'iter_rows'
What is the problem?
问题是什么?
采纳答案by DNA
As shown in the tutorial, you need to call the iter_rows
method on an instance of a worksheet, for example:
如教程中所示,您需要iter_rows
在工作表的实例上调用该方法,例如:
>>> for row in ws.iter_rows('A1:C2'):
... for cell in row:
... print cell
or
或者
>>> 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>
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:
正如您的错误消息所述,您在Worksheet
type上调用它,这将不起作用;它需要在一个对象上调用:
op.worksheet.Worksheet.iter_rows() # wrong
See also this examplein another answer.
另请参阅另一个答案中的此示例。
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.
对于旧版本的 openpyxl,您可能需要确保在加载工作簿时启用迭代器 - 请参阅此线程。对于较新的版本,这不是必需的。
Here's a complete example which I just tested in the Python REPL (with openpyxl 1.8.3):
这是我刚刚在 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')
...