• 技术文章 >Python技术 >Python基础教程

    关于Python中openpyxl使用iter_rows()的方法

    2020-10-27 16:40:19原创17597
    之前已经对iter函数的用法有过讲解,记忆遗忘的小伙伴可以重新回顾一遍。今天就iter函数的拓展,讲讲openpyxl中导入iter_rows()的方法。


    当我们使用以下代码:


    1

    2

    3

    4

    5

    6

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">import openpyxl as op

    ms = op.load_workbook('mtest.xlsx')

     

    ws = ms.active

     

    op.worksheet.Worksheet.iter_rows()<br></span></p>


    然后会出现,此代码返回:


    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">type object 'Worksheet' has no attribute 'iter_rows'<br></span></p>


    怎么会出现这种情况?

    这说明,您需要在工作表的实例上调用iter_rows方法,例如:


    1

    2

    3

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">>>> for row in ws.iter_rows('A1:C2'):

    ...        for cell in row:

    ...            print cell<br></span></p>


    要么


    1

    2

    3

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):

    ...    for cell in row:

    ...        print(cell) <br></span></p>


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


    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">op.worksheet.Worksheet.iter_rows()  # wrong<br></span></p>


    对于旧版本的openpyxl,您可能需要确保在加载工作簿时启用迭代器 –对于更新版本,这不是必需的。

    以下是一个完整的例子在Python REPL中测试过(使用openpyxl 1.8.3):


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">>>> 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')

    ...<br></span></p>


    还没有学会的小伙伴不要着急,结合之前学习再重新看一遍今天的示例,Python基础知识回顾:iter函数

    专题推荐:openpyxl使用iter_rows;python
    上一篇:python正则表达式是什么?怎么用? 下一篇:Python基础:使用 openpyxl为Excel设置行高或者列宽

    相关文章推荐

    • 在pycharm中用不了openpyxl怎么办?• 做表繁杂?Python中openpyxl的用处• Python实用之安装openpyxl• Python基础:iter函数的两个参数

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网