Can't save a workbook after deleting sheets -

2019-06-24 04:03发布

问题:

I'm manipulating a sheet, mainly deleting all the sheets but the one that I need. I will loop through all the sheets, and delete the sheets that is not useful for my task.

After deleting, I tried to save but it throws an error.

File "C:\Users\myUser\Anaconda3\lib\site-packages\openpyxl\workbook\workbook.py", line 130, in active
return self._sheets[self._active_sheet_index]

Here's my script

wb = load_workbook("File.xlsx")

ws1 = wb["Employee Info"]
ws1.freeze_panes = None

ws_active = wb.get_sheet_by_name("Employee Info")

### delete other sheets but Employee Info
for sheet in wb.worksheets:
    if sheet.title != 'Employee Info':
        print("removing " + sheet.title)
        wb.remove_sheet(sheet)

print("remaining sheets:")
for sheet in wb.worksheets:
    print("    " + sheet.title)

### TODO
### loop through the files in a directory

### TODO
### see if readable by ETL 

print("saving the wb")

wb.save("modified.xlsx")

after deleting, I checked the workbook. And it has the sheet that I am looking for. Just not sure though why it is not detecting the remaining 1 sheet.

To add more details, the excel file has 8 sheets, the sheet that I am after is on the 5th sheet.

回答1:

For me this is working with 2.4.2 version:

import openpyxl

workbook = openpyxl.load_workbook('test.xlsx')

for i in workbook.worksheets:
    if i.title != 'Employee Info':
        workbook.remove_sheet(i)

workbook.save('test2.xlsx')

Try it simple to see if its working. You can also use the workbook.sheetnames to see the sheetnames:

for sheet in workbook.sheetnames:
    print(sheet)


回答2:

wb.remove_sheet() is deprecated from the official documentation. I can't comment yet, but do you get the same error when using wb.remove()?



回答3:

Before saving, you can use as a workaround:

wb.active = 0

Update to 2.4.2, last change reads: workbook.py Fail gracefully when the active sheet is deleted.