Python Excel

Deleting a Sheet in openpyxl

Deleting a sheet cannot be undone inside the workbook. List the sheet names first, delete the one you mean, then save. Practice on a copy.

  1. Load the workbook.
  2. Print the sheet names.
  3. Choose the sheet to remove.
  4. Delete it.
  5. Save the workbook.
  6. Load it again and confirm the name is gone.

Example

Create an empty file named testdel.xlsx with the usual Sheet1, Sheet2, and Sheet3. Then run:

import openpyxl

wb = openpyxl.load_workbook("testdel.xlsx")
print(wb.sheetnames)
# ['Sheet1', 'Sheet2', 'Sheet3']

del wb["Sheet2"]
print(wb.sheetnames)
# ['Sheet1', 'Sheet3']

wb.save("testdel.xlsx")

What each line does

load_workbook reads testdel.xlsx into memory. sheetnames shows the tabs without changing them. del wb["Sheet2"] removes that worksheet. You can also write wb.remove(wb["Sheet2"]). Both need the worksheet, not a bare name passed to the old remove_sheet method. That method has been removed from current openpyxl.

The file on disk is unchanged until save. Pass a different filename if you want to keep the original next to the edited copy:

wb.save("testdel-without-sheet2.xlsx")

Loading a workbook is covered in load_workbook. Adding sheets is covered in Python Excel Writer.