pythonopenpyxl

How to delete a sheet from a workbook using openpyxl?


I want to delete a sheet from my Excel file.

I tried this code:

import openpyxl

workbook1 = openpyxl.load_workbook(input_file_folder + input_file_name)
print(workbook1.sheetnames)
Sheet1 = workbook1['Sheet1']
workbook1.remove(Sheet1)
workbook1.save(input_file_folder + input_file_name)
writer.save()

The sheet names are printing out to be:

['Sheet1', 'Candidate Campaign 0', 'Candidate Campaign 6', 'Candidate Campaign 7', 'Candidate Campaign 8', 'Valid Campaigns']

But somehow the "Sheet1' is not getting deleted anyhow.

I even tried:

n = workbook1.sheetnames
workbook1.remove(n[1])

but this doesn't work as well.

Can anyone please pinpoint what's wrong. As this command is working with other sheets but only Sheet1(the default one) is not getting deleted.


Solution

  • As suggested by Charlie Clark in the comments:

    
    del workbook1['Sheet1']