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

I'm using openpyxl package in Python(Canopy) to use excel files. We have this tutorial in this link : LINK

you can also use the openpyxl.worksheet.Worksheet.iter_rows() method:

>>> tuple(ws.iter_rows('A1:C2'))

((, , ),

(, , ))

>>> for row in ws.iter_rows('A1:C2'):

... for cell in row:

... print cell

How we can import openpyxl.worksheet.Worksheet.iter_rows() method in python? I used this code:

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?

解决方案

As shown in the tutorial, you need to call the iter_rows method on an instance of a worksheet, for example:

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

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:

op.worksheet.Worksheet.iter_rows() # wrong

See also this example in 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.

Here's a complete example which I just tested in the Python REPL (with 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')

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值