Openpyxl How to get row from worksheet by index

后端 未结 2 1722
有刺的猬
有刺的猬 2021-02-07 10:11

Using Openpyxl and python3.5, I tried getting the first row from an excel worksheet using a subscript but I an error.

# after getting filename
# after loading w         


        
相关标签:
2条回答
  • 2021-02-07 10:41

    I finally found the answer in the documentation:

    first_row = worksheet[1]
    # worksheet[row_index_from_1]
    

    This worked for me.

    0 讨论(0)
  • 2021-02-07 10:41

    The error TypeError: 'generator' object is not subscriptable. Means that you are trying to access by index a generator, which doesn't have one, because it creates the elements as you iterate through it.

    You can solve it easily, cast it to a list to get the element you want:

    first_row = list(worksheet.rows)[0]
    

    or iterate thought the rows:

    for row in worksheet.rows:
        foo(row)
    

    This is because, even if both are iterables, lists and generators can behave quite differently, you can get it better explained here:

    https://wiki.python.org/moin/Generators

    https://docs.python.org/3/library/stdtypes.html#iterator-types

    https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range

    0 讨论(0)
提交回复
热议问题