How to use Worksheet.Parent in the xlwings API way

The Parent property of a Worksheet object in the Excel object model is a fundamental attribute that provides a reference to the workbook containing the worksheet. In xlwings, this property is accessible through the api property, which exposes the underlying Excel object model, allowing for direct interaction with Excel’s native features. Understanding and utilizing the Parent property is essential for navigating between worksheets and workbooks programmatically, especially when dealing with multiple workbooks or when you need to reference the parent workbook for operations such as saving, closing, or accessing other worksheets.

Functionality:
The primary function of the Parent property is to return the parent object of a worksheet, which is always a Workbook object in Excel. This enables developers to access workbook-level properties and methods from a worksheet instance, facilitating tasks like workbook management, cross-sheet references, and dynamic operations that depend on the workbook context.

Syntax:
In xlwings, you access the Parent property through the api property of a Worksheet object. The syntax is straightforward:

worksheet.api.Parent

Here, worksheet is an instance of a xlwings Worksheet object. The Parent property does not take any parameters and returns a COM object representing the parent workbook. You can then use this object to call workbook-specific methods or access properties.

Example Usage:
Consider a scenario where you have an Excel workbook with multiple worksheets, and you want to retrieve the name of the parent workbook from a specific worksheet. Using xlwings, you can achieve this as follows:

import xlwings as xw

# Connect to the active workbook or open a specific one
app = xw.App(visible=False) # Run Excel in the background
workbook = app.books.open('example.xlsx') # Open a workbook
worksheet = workbook.sheets['Sheet1'] # Access a specific worksheet

# Access the Parent property to get the workbook object
parent_workbook = worksheet.api.Parent

# Retrieve the name of the parent workbook
workbook_name = parent_workbook.Name
print(f"The parent workbook name is: {workbook_name}")

# You can also perform workbook-level operations, such as saving
parent_workbook.Save()

# Close the workbook and quit Excel
workbook.close()
app.quit()

September 28, 2026 (0)


Leave a Reply

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