Using openpyxl, I want to delete all sheets containing some keywords. My sheet title for example are
['ABC-123','ABC-456','DEF-123','DEF-456','GHI-123','GHI-456','JKL-123','JKL-456']
List of keywords for sheets I want to keep
['GHI','JKL']
In the end, if the code executes correctly. The remaining sheet titles should be:
['GHI-123','GHI-456','JKL-123','JKL-456']
My code example below:
file = 'z:\\excel\\test.xlsx'
wb = openpyxl.load_workbook(file)
ws = wb.active
list_of_sheets_to_keep = ['GHI','JKL']
numbers_of_sheets = len(sheet_names)
i = 0
for i in range(numbers_of_sheets):
x = wb.sheetnames[i]
s = wb[str(x)]
sheet = str(s.title)
if sheet[:3] not in list_of_sheets_to_keep:
print('Deleting sheet: ' + sheet + '\n because it is not in the List of Sheets to Keep')
del wb[sheet] # this doesn't work
# wb.remove(sheet) # and this doesn't work either
# del wb[title] # doesn't work either
I get this error for del wb[sheet]:
Traceback (most recent call last):
File "Z:\excel\test.py", line 31, in <module>
x = wb.sheetnames[i]
IndexError: list index out of range
and this error for wb.remove(sheet):
Traceback (most recent call last):
File "Z:\excel\test.py", line 39, in <module>
wb.remove(sheet)
File "Z:\.virtualenvs\excel-kLb3DFP1\lib\site-packages\openpyxl\workbook\workbook.py", line 233, in remove
idx = self._sheets.index(worksheet)
ValueError: 'ABC-123' is not in list
and lastly del wb[title] doesn't work either:
Traceback (most recent call last):
File "Z:\excel\test.py", line 38, in <module>
del wb[ws.title]
File "Z:\excel-kLb3DFP1\lib\site-packages\openpyxl\workbook\workbook.py", line 292, in __delitem__
sheet = self[key]
File "Z:\.virtualenvs\excel-kLb3DFP1\lib\site-packages\openpyxl\workbook\workbook.py", line 289, in __getitem__
raise KeyError("Worksheet {0} does not exist.".format(key))
KeyError: 'Worksheet ABC-123 does not exist.'