V. Brunelle
V. Brunelle

Reputation: 1068

Get Worksheet index from title or instance using Openpyxl

How can someone get the Worksheet's index number using a Worksheet's property with Openpyxl?

The best example would be an Excel workbook that contains 3 sheets: "Aaa", "Bbb" and "Ccc". Knowing the title "Bbb", what would be the way of getting the index number of that sheet?

Upvotes: 2

Views: 9368

Answers (2)

V. Brunelle
V. Brunelle

Reputation: 1068

wb.worksheets.index(wb.get_sheet_by_name('Bbb')) is the right answer. Thanks to BeeR for pointing it out.

Edit: With Openpyxl's update, the correct syntax would be

wb.worksheets.index(wb['Bbb'])

Upvotes: 3

BeeR
BeeR

Reputation: 11

Unfortunately, this does not work for me.

For this code:

(...)
print(workbook.sheetnames)
print(workbook.worksheets.index('1.3'))

I get the following error:

['Übersicht', '1.1', '1.2', '1.3', '1.4', '1.5', '1.6', '1.7', '1.8', '2.1', '2.2', '2.3', '2.4', '2.5', '2.6', '2.7', '2.8', '3.1'] File ".../xlsx_tests.py", line 159, in print(workbook.worksheets.index('1.3')) ValueError: '1.3' is not in list

Upvotes: 1

Related Questions