openpyxl: remove_sheet causes IndexError: list index out of range error on saving sheet
Created originally on Bitbucket by Jim98 (Jim Pisano)
Python 3.4.4 / Excel 2016 / openpyxl 2.4.1
I am trying to use openpyxl to:
-
Open an Excel (2016) workbook which contains 3 worksheets (Sheet1,Sheet2,Sheet3)
-
Remove a worksheet (Sheet2)
-
Save the workbook to a different workbook minus Sheet2
#!python
from openpyxl import load_workbook
wb = load_workbook("c:/Users/me/book1.xlsx")
ws = wb.get_sheet_by_name('Sheet2')
wb.remove_sheet(ws)
wb.save("c:/Users/me/book2.xlsx")
The wb.save will generate an IndexError: list index out of range error and produce a corrupted book2.xlsx file which Excel cannot open.
The above code generates the following error
#!python
C:\Python34\python.exe C:/Users/jpisano/PycharmProjects/junk/test.py
Traceback (most recent call last):
File "C:/Users/jpisano/PycharmProjects/junk/test.py", line 18, in <module>
wb.save("c:/Users/jpisano/book2.xlsx")
File "C:\Python34\lib\site-packages\openpyxl\workbook\workbook.py", line 339, in save
save_workbook(self, filename)
File "C:\Python34\lib\site-packages\openpyxl\writer\excel.py", line 268, in save_workbook
writer.save(filename)
File "C:\Python34\lib\site-packages\openpyxl\writer\excel.py", line 250, in save
self.write_data()
File "C:\Python34\lib\site-packages\openpyxl\writer\excel.py", line 93, in write_data
archive.writestr(ARC_WORKBOOK, write_workbook(self.workbook))
File "C:\Python34\lib\site-packages\openpyxl\writer\workbook.py", line 88, in write_workbook
active = get_active_sheet(wb)
File "C:\Python34\lib\site-packages\openpyxl\writer\workbook.py", line 60, in get_active_sheet
sheet = wb.active
File "C:\Python34\lib\site-packages\openpyxl\workbook\workbook.py", line 130, in active
return self._sheets[self._active_sheet_index]
IndexError: list index out of range
Process finished with exit code 1
Attachments: Book1.xlsx