How to use Worksheets.Move in the xlwings API way
The Move member of the Worksheets object in Excel’s object model allows for repositioning a worksheet within a workbook. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model. This is particularly useful for organizing sheets in a specific order, such as moving a newly created sheet to the beginning or end of the workbook.
Functionality:
The Move method relocates a specified worksheet to a new position relative to other sheets. It can place the sheet before or after another worksheet, enabling precise control over the sheet order. This is essential for creating reports or dashboards where the sequence of sheets impacts usability and presentation.
Syntax:
In xlwings, the syntax for moving a worksheet is:
worksheet.api.Move(Before, After)
- Before (optional): A
Worksheetobject representing the sheet before which the moved sheet will be placed. If specified, the moved sheet is positioned immediately before this sheet. - After (optional): A
Worksheetobject representing the sheet after which the moved sheet will be placed. If specified, the moved sheet is positioned immediately after this sheet.
Notes:
- You must specify either
BeforeorAfter, but not both. If both are omitted, Excel creates a new workbook containing the moved sheet. - The parameters accept
Worksheetobjects, which can be obtained via xlwings (e.g.,wb.sheets['SheetName']). - Moving a sheet does not affect its content or formatting, only its position in the workbook tab order.
Code Examples:
- Move a sheet to the beginning of the workbook:
import xlwings as xw
wb = xw.Book('workbook.xlsx')
target_sheet = wb.sheets['DataSheet']
first_sheet = wb.sheets[0] # Get the first sheet
target_sheet.api.Move(Before=first_sheet.api)
This moves ‘DataSheet’ to appear before the first sheet, making it the new first sheet.
- Move a sheet to the end of the workbook:
import xlwings as xw
wb = xw.Book('workbook.xlsx')
target_sheet = wb.sheets['ReportSheet']
last_sheet = wb.sheets[-1] # Get the last sheet
target_sheet.api.Move(After=last_sheet.api)
This positions ‘ReportSheet’ after the last sheet, placing it at the end.
- Move a sheet relative to another specific sheet:
import xlwings as xw
wb = xw.Book('workbook.xlsx')
sheet_to_move = wb.sheets['Sheet1']
reference_sheet = wb.sheets['Sheet3']
sheet_to_move.api.Move(After=reference_sheet.api)