Home > Software engineering >  openpyxl - avoid error if bad sheert name used
openpyxl - avoid error if bad sheert name used

Time:07-20

I am trying to avoid an unrecoverable error using openpyxl if a bad tab/sheet name is used. Here are the lines of python:

try:
    sheet = workbook[month_list[int(month)-1]   day]
except SheetTitleException as e:
    print("worksheet does not exist")

If a valid name is constructed, everything is fine. If not i get the following error:

raise KeyError("Worksheet {0} does not exist.".format(key))

KeyError: 'Worksheet Jan01 does not exist.'

I am trying to catch and recover from the mistake. Can someone please correct what i have done.

Thanks for any/all suggestions.

CodePudding user response:

I think it would be better to check if the name exists in the sheetnames. Openpyxl has a workbook.sheetnames, which will give you a list of the names of all worksheets in the workbook. So, try this...


names = workbook.sheetnames
if str(month_list[int(month)-1]   day) not in names:
    print("worksheet does not exist")
else:
    print("All ok")
    # Your code here...

 

CodePudding user response:

Either way the exception is a key error. You would need to handle the exception trying another sheet so a simple example.
The try catch will try to open 'Sheet1', 'Sheet2' etc until it succeeds (indefinitely in this example).

wb = op.load_workbook('excelfile.xlsx')
count = 1
while True:
    try:
        sheet = wb['Sheet{0}'.format(count)]
        break
    except KeyError as e: # <-- This is the exception
        print("worksheet {0} does not exist".format(count))
        count  = 1
  • Related