How to use Worksheets.Delete in the xlwings API way

The Delete member of the Worksheets collection in the Excel object model is a method used to remove a specified worksheet from a workbook. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model, allowing for precise control over worksheet management. This method is particularly useful for automating the cleanup of temporary sheets, restructuring workbooks dynamically, or removing unnecessary data sheets in batch processing scenarios. Understanding its usage in xlwings ensures efficient workbook manipulation while maintaining compatibility with Excel’s native behavior.

Functionality
The Delete method permanently deletes a worksheet from the workbook. It does not move the sheet to the Recycle Bin; once deleted, the sheet cannot be recovered unless the workbook is closed without saving. In xlwings, this operation is performed by accessing the Excel API, so it mirrors the exact behavior of Excel’s VBA Delete method. This includes any prompts or warnings Excel might display, depending on the application settings.

Syntax
In xlwings, the Delete method is called via the api property on a Worksheet object. The syntax is:
worksheet.api.Delete()
Here, worksheet refers to an xlwings Worksheet object (e.g., obtained through wb.sheets['SheetName'] or wb.sheets[0]). The method does not take any parameters in its basic form. However, in Excel’s object model, the Delete method can be influenced by the application’s display alerts. To suppress confirmation dialogs, you can set xlwings.App().api.DisplayAlerts = False before deletion and restore it to True afterward.

Example
Below is a code example demonstrating the usage of the Delete member with xlwings. This example assumes you have an existing workbook with multiple sheets and want to remove a specific sheet programmatically.

import xlwings as xw

# Connect to an existing workbook (adjust the path as needed)
wb = xw.Book('example.xlsx')

# Access a specific worksheet by name
sheet_to_delete = wb.sheets['TempSheet']

# Disable Excel alerts to avoid confirmation prompts
app = xw.apps.active
app.api.DisplayAlerts = False

# Delete the worksheet
sheet_to_delete.api.Delete()

# Re-enable alerts
app.api.DisplayAlerts = True

# Save the workbook to persist changes
wb.save()

# Close the workbook (optional)
wb.close()

August 20, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *