The Delete member of the Worksheet object in the Excel object model, accessible via the xlwings API in Python, provides a programmatic way to remove a specific worksheet from a workbook. This operation is irreversible through the API itself (akin to manually deleting a sheet and not saving the workbook), so it should be used with caution, especially on unsaved workbooks where data loss can occur.
Functionality
The primary function of the Delete method is to permanently delete the worksheet object on which it is called. After deletion, the worksheet is removed from the workbook’s Worksheets collection. If the deleted sheet was the only sheet in the workbook, xlwings and Excel will typically prevent its deletion to maintain at least one visible sheet, as an Excel workbook must contain at least one visible worksheet.
Syntax & Parameters
In xlwings, the method is called directly on a Sheet object (which represents a worksheet or chart sheet). The xlwings API abstracts the underlying COM calls into a simple Python method call.
sheet.delete()
There are no parameters for this method in the standard xlwings API. The action is applied to the sheet object referenced. It’s important to note that the Sheet object in xlwings corresponds to what the Excel Object Model calls a Worksheet (for standard worksheets) or a Chart object (for chart sheets). The delete() method works on both.
Code Examples
- Basic Deletion of a Specific Sheet:
This example opens a workbook and deletes a sheet named “SheetToRemove”.
import xlwings as xw
# Open the workbook (use full path if needed)
wb = xw.Book("example.xlsx")
# Access the specific worksheet
sheet_to_delete = wb.sheets["SheetToRemove"]
# Delete the worksheet
sheet_to_delete.delete()
# Save the workbook to persist the change
wb.save()
wb.close()
- Deleting the Active Sheet:
This example deletes whichever sheet is currently active in the open workbook.
import xlwings as xw
app = xw.App(visible=False) # Start Excel in the background
wb = app.books.open("data.xlsx")
# Delete the active sheet
wb.sheets.active.delete()
wb.save("data_modified.xlsx")
wb.close()
app.quit()
- Conditional Deletion Based on Content:
A more practical example involves checking sheet names or content before deletion. This script deletes all sheets whose name contains the word “Temp”.
import xlwings as xw
wb = xw.Book("report.xlsx")
# Create a list of sheets to delete first to avoid iteration issues
sheets_to_delete = [sht for sht in wb.sheets if "Temp" in sht.name]
for sht in sheets_to_delete:
print(f"Deleting sheet: {sht.name}")
sht.delete()
wb.save()
Leave a Reply