The Delete method of the Range object in Excel is a powerful tool for removing cells, rows, or columns from a worksheet, shifting the surrounding cells to fill the space. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model. Understanding how to use Delete effectively is essential for data manipulation and cleanup tasks.
Functionality:
The Delete method removes the specified range and shifts adjacent cells. The direction of the shift is determined by the Shift argument. This is useful for deleting unwanted data, removing blank rows/columns, or dynamically restructuring a worksheet. Unlike simply clearing contents, Delete physically removes the cells, altering the worksheet layout.
Syntax:
In xlwings, the syntax for calling the Delete method is:
range.api.Delete(Shift)
Where range is an xlwings Range object, and Shift is an optional parameter that specifies how to shift cells to replace the deleted ones. The Shift parameter can be one of the following constants from the xlwings.constants module (or their equivalent numeric values):
| Constant (from xlwings.constants) | Value | Description |
|---|---|---|
xlShiftToLeft | -4159 | Shifts cells to the left. |
xlShiftUp | -4162 | Shifts cells upward. |
If the Shift argument is omitted, Excel will default to shifting cells up (xlShiftUp) for entire rows and to the left (xlShiftToLeft) for entire columns. For smaller ranges that are not entire rows/columns, Excel uses the default based on the shape of the range.
Examples:
Here are several xlwings API code instances demonstrating the use of Range.Delete.
- Delete a single cell and shift up:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
sheet = wb.sheets['Sheet1']
# Delete cell B2 and shift the cells below it upward
sheet.range('B2').api.Delete()
wb.save()
app.quit()
- Delete a range of rows:
import xlwings as xw
from xlwings.constants import DeleteShiftDirection
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
sheet = wb.sheets['Sheet1']
# Delete rows 5 through 7, shifting cells up
sheet.range('5:7').api.Delete(Shift=DeleteShiftDirection.xlShiftUp)
wb.save()
app.quit()
- Delete a column and shift left:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
sheet = wb.sheets['Sheet1']
# Delete column C, shifting columns to the right of it leftward
sheet.range('C:C').api.Delete()
wb.save()
app.quit()
- Delete a non-contiguous range:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
sheet = wb.sheets['Sheet1']
# Delete cells A1:B2 and D1:D3, shifting cells up for each area
delete_range = sheet.range('A1:B2, D1:D3')
delete_range.api.Delete()
wb.save()
app.quit()
Leave a Reply