pythonexcelindexingopenpyxl

Openpyxl How to get row from worksheet by index


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


Solution

  • I finally found the answer in the documentation:

    first_row = worksheet[1]
    # worksheet[row_index_from_1]
    

    This worked for me.