Openpyxl How to get row from worksheet by index

纵然是瞬间 提交于 2019-12-05 17:49:13

问题


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 worksheet
# to get the first row of the worksheet
first_row = worksheet.rows[0]

# I get 
Traceback (most recent call last):
      File "<pyshell#54>", line 1, in <module>
      first_row = phc_th_sheet.rows[1]
TypeError: 'generator' object is not subscriptable

In relation to getting the first row, I've also tried first_row = worksheet.(row=1) # and first_row = worksheet.rows[:1]

None worked. Any suggestions or is the feature not available in openpyxl? I've been to the documentation at https://openpyxl.readthedocs.io/en/default/ but I found nothing helpful enough to index and select rows


回答1:


I finally found the answer in the documentation:

first_row = worksheet[1]
# worksheet[row_index_from_1]

This worked for me.




回答2:


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



来源:https://stackoverflow.com/questions/40561670/openpyxl-how-to-get-row-from-worksheet-by-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!