Openpyxl How to get a row from a worksheet by index

Using Openpyxl and python3.5, I tried to get the first row from an excel sheet using an index, but I made a mistake.

# 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

Regarding getting the first line, I also tried first_row = worksheet (line = 1) # as well as first_row = workheet.rows [: 1]

Does not work. Any suggestions or feature not available in openpyxl? I was in the documentation at https://openpyxl.readthedocs.io/en/default/ , but did not find anything useful for indexing and row selection

+4
source share
2 answers

Finally, I found the answer in the documentation:

first_row = worksheet.rows[1]
# worksheet.rows[row_index_from_1]

It worked for me.

+13
source

TypeError: 'generator' object is not subscriptable. , , , .

, , :

first_row = list(worksheet.rows)[0]

:

for row in worksheet.rows:
    foo(row)

, , , -, :

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

+8

Source: https://habr.com/ru/post/1660566/


All Articles