Archive

How to use Workbook.Application in the xlwings API way

The Application member of a Workbook object in xlwings provides a gateway to the overarching Excel application instance. This is a powerful property because it allows you to control Excel-wide settings, access other open workbooks, and interact with application-level features directly from a specific workbook context. Essentially, Workbook.app (or the full property Workbook.application) returns the main App object to which the workbook belongs, enabling you to scale your automation from a single file to the entire Excel environment.

Functionality:
The primary function is to retrieve the parent App object. Through this App object, you can:

  • Control Excel application settings (e.g., DisplayAlerts, ScreenUpdating, Calculation).
  • Access all open workbooks via the App.books collection.
  • Create new workbooks or open existing ones at the application level.
  • Quit the Excel application entirely.

Syntax:
The access is straightforward as it is a property.

app_instance = my_workbook.app
# or equivalently
app_instance = my_workbook.application
  • my_workbook: A xlwings Book object (the Python representation of an Excel Workbook).
  • app_instance: The returned xlwings App object. This object has its own set of properties and methods.

Code Examples:

  1. Accessing Application Properties from a Workbook:
    This example shows how to disable screen updating and alerts via the App object retrieved from a specific workbook, perform an operation, and then restore the settings.
import xlwings as xw

# Connect to an existing workbook
wb = xw.Book("Report.xlsx")

# Get the parent Excel Application
excel_app = wb.app

# Configure application-wide settings
excel_app.screen_updating = False
excel_app.display_alerts = False

# Perform operations (e.g., add a new sheet)
new_sheet = wb.sheets.add("NewData")

# Restore settings
excel_app.screen_updating = True
excel_app.display_alerts = True
  1. Listing All Open Workbooks:
    Using the App object from one workbook to interact with others.
import xlwings as xw

wb1 = xw.Book("Financials.xlsx")
app = wb1.app

print("Workbooks currently open in this Excel instance:")
for open_wb in app.books:
    print(f" - {open_wb.name}")
  1. Creating a New Workbook in the Same Instance:
    Ensures a new workbook is created in the same Excel application window as your current workbook.
import xlwings as xw

source_wb = xw.Book("SourceData.xlsx")
app = source_wb.app

# Create a new workbook in the same Excel instance
new_wb = app.books.add()
new_wb.sheets[0].range("A1").value = "Report Generated from " + source_wb.name

How to use Workbook.OpenXML in the xlwings API way

In Excel object model, the OpenXML property of the Workbook object provides a way to access the underlying Open XML representation of a workbook. This is particularly useful for developers who need to perform custom XML manipulations, such as reading or modifying specific parts of the workbook’s structure that are not directly exposed through the standard Excel object model. The OpenXML property returns a string that contains the raw XML data of the workbook in the Office Open XML format, enabling advanced automation and integration scenarios. In xlwings, this functionality can be accessed via the api property, which exposes the native Excel object model.

The syntax for accessing the OpenXML property in xlwings is straightforward. Since xlwings uses the underlying COM object model, you can call it directly on a workbook object. The property does not take any parameters and returns a string. Here’s the basic format:

workbook.openxml

In this syntax, workbook refers to an xlwings Book object that represents an open workbook. The openxml property is accessed through the api attribute to get the native Excel Workbook object’s OpenXML property. Note that this property is read-only in the context of xlwings, meaning you can retrieve the XML data but not set it directly through this property. To modify the XML, you would typically use additional libraries like openpyxl or lxml to parse and edit the string, then save it back if needed.

For example, consider a scenario where you need to extract custom XML data from an Excel workbook to analyze metadata or embedded schemas. Using xlwings, you can open a workbook and retrieve its Open XML representation. Here’s a code instance:

import xlwings as xw

# Open an existing workbook
wb = xw.Book('example.xlsx')

# Access the OpenXML property via the api
openxml_data = wb.api.OpenXML

# Print or process the XML data (first 500 characters for brevity)
print(openxml_data[:500])

# You can also save the XML to a file for further analysis
with open('workbook_openxml.xml', 'w', encoding='utf-8') as f:
    f.write(openxml_data)

# Close the workbook if needed
wb.close()

How to use Workbook.OpenText in the xlwings API way

The OpenText method in the Workbook object is a powerful feature for importing and parsing text files directly into Excel using xlwings. It allows for automated data ingestion from various delimited text formats, such as CSV or tab-separated files, into a structured Excel workbook. This method is particularly useful for data analysts and developers who need to streamline workflows by eliminating manual import steps. By leveraging xlwings, users can programmatically control the import process, specifying parameters like delimiters, data types, and starting cell positions to ensure data is correctly formatted upon entry.

Syntax and Parameters:
In xlwings, the OpenText method is accessed through a Workbook object. The basic API call follows this format:
workbook.api.OpenText(Filename, ...)
Here, workbook refers to an xlwings Book object, and .api provides access to the underlying Excel object model. The method requires the Filename parameter, which is a string specifying the path to the text file. Additional optional parameters can be set to customize the import. Key parameters include:

  • Origin: Specifies the file origin (e.g., xlWindows for Windows).
  • StartRow: The row number at which to start importing data (default is 1).
  • DataType: Sets column data types, using constants like xlGeneralFormat for general data.
  • TextQualifier: Defines the text qualifier character, such as xlTextQualifierDoubleQuote.
  • ConsecutiveDelimiter: A Boolean indicating whether consecutive delimiters should be treated as one.
  • Tab, Semicolon, Comma, Space, Other: Boolean parameters to set the delimiter type, with Other allowing a custom delimiter via OtherChar.
  • FieldInfo: An array specifying detailed parsing for each column, including data types and delimiters.

For example, to import a comma-delimited file with specific settings, you might set Comma=True and DataType=xlTextFormat for text columns. The FieldInfo parameter is often provided as a list of tuples, where each tuple corresponds to a column and includes a column number and data type constant.

Code Example:
Below is an xlwings Python code snippet demonstrating the use of OpenText to import a CSV file. This example assumes Excel is running and a workbook is active:

import xlwings as xw

# Connect to the active Excel instance and workbook
app = xw.apps.active
wb = app.books.active

# Define the text file path
file_path = r'C:\Data\sample.csv'

# Use OpenText to import the file with custom settings
wb.api.OpenText(Filename=file_path,
Origin=xw.constants.xlWindows,
StartRow=1,
DataType=xw.constants.xlDelimited,
TextQualifier=xw.constants.xlTextQualifierDoubleQuote,
ConsecutiveDelimiter=False,
Comma=True,
FieldInfo=[(1, xw.constants.xlGeneralFormat),
(2, xw.constants.xlTextFormat),
(3, xw.constants.xlMDYFormat)])

# Save the workbook with the imported data
wb.save(r'C:\Data\output.xlsx')

How to use Workbook.OpenDatabase in the xlwings API way

The OpenDatabase method of the Workbook object in Excel is a powerful feature for connecting to and retrieving data from external databases directly into an Excel workbook. This method enables you to establish a connection to a database source (such as Microsoft Access, SQL Server, or other ODBC-compliant databases) and execute SQL queries to import data. In xlwings, this functionality is accessible through the Workbook object’s API, allowing you to automate database queries and data integration within your Python scripts. It is particularly useful for automating reports, dashboards, and data analysis tasks that require fresh data from corporate databases.

Syntax in xlwings:
The OpenDatabase method can be called on a Workbook object. The basic syntax in xlwings is:

workbook.api.OpenDatabase(Connection, CommandText, CommandType, BackgroundQuery, ImportDataAs)

Parameters:

  • Connection: A string specifying the connection string to the database. This includes details like the data source provider, server name, database name, and authentication credentials.
  • CommandText: A string that defines the SQL query or command to execute, such as “SELECT * FROM SalesData”.
  • CommandType: An optional parameter that specifies the command type. Common values are xlCmdSQL (default for SQL queries) or xlCmdTable (for direct table access). In xlwings, you can use Excel constants like win32c.xlCmdSQL (on Windows) or their numeric equivalents (e.g., 1 for xlCmdSQL).
  • BackgroundQuery: An optional boolean parameter (True or False) that determines if the query runs in the background. If True, Excel allows other operations while the query executes.
  • ImportDataAs: An optional parameter that specifies how to import the data. For example, you can use win32c.xlPivotTableReport to create a PivotTable or win32c.xlTable for a standard table. The default is to import as a simple range.

Example:
Below is an xlwings code example that demonstrates using OpenDatabase to import data from a Microsoft Access database into an Excel workbook. This example assumes you have an Excel file open via xlwings and a valid Access database file.

import xlwings as xw
import win32com.client

# Connect to the active Excel workbook
wb = xw.books.active

# Define the connection string for an Access database (adjust the path as needed)
connection_str = "ODBC;DSN=MS Access Database;DBQ=C:\\Path\\To\\Your\\Database.accdb;"

# Define the SQL query
sql_query = "SELECT * FROM Orders WHERE OrderDate >= #2023-01-01#"

# Call OpenDatabase via the Excel API
# Note: We use wb.api to access the underlying Workbook object from Excel's object model
wb.api.OpenDatabase(
Connection=connection_str,
CommandText=sql_query,
CommandType=win32com.client.constants.xlCmdSQL, # Use constant for SQL command
BackgroundQuery=False, # Run query in foreground
ImportDataAs=win32com.client.constants.xlTable # Import as a table
)

# Optional: Save the workbook to persist the data
wb.save()

How to use Workbook.Open in the xlwings API way

The Open member of the Workbook object in xlwings is a method used to open an existing Excel workbook file. This function is essential for automating tasks that involve reading from or writing to pre-existing spreadsheets, enabling seamless integration of Excel files into Python-based data analysis and reporting workflows. By using Open, you can programmatically access workbooks without manually opening Excel, which is particularly useful for batch processing, data extraction, and automated updates.

Syntax and Parameters:
In xlwings, the Open method is typically accessed through the books collection of the App object. The basic syntax is:

wb = xw.books.open(path)

Here, path is a required string parameter specifying the file path to the Excel workbook. It can be an absolute or relative path, and it should include the file extension (e.g., .xlsx, .xls). The method returns a Book object, which represents the opened workbook, allowing you to manipulate its sheets, ranges, and data.

The open method also supports additional optional parameters to control how the workbook is opened, though these are less commonly used in basic scenarios. For example, you can specify update links, read-only mode, or password protection. In xlwings, these parameters align with Excel’s Workbooks.Open method, but the implementation is simplified. A common parameter is read_only, which can be set to True to open the workbook in read-only mode, preventing accidental modifications. For instance:

wb = xw.books.open('example.xlsx', read_only=True)

This opens the workbook without allowing edits, which is useful for data extraction tasks where integrity is crucial.

Example Usage:
Below are practical code examples demonstrating the use of the Open method in xlwings. Ensure you have xlwings installed (pip install xlwings) and that Excel is available on your system.

  1. Basic Example – Opening a Workbook:
    This example opens an Excel file located in the current directory and prints the names of all its sheets.
import xlwings as xw
# Open the workbook
wb = xw.books.open('sales_data.xlsx')
# List all sheet names
sheet_names = [sheet.name for sheet in wb.sheets]
print("Sheet names:", sheet_names)
# Close the workbook after use (optional, as xlwings may handle it automatically)
wb.close()

In this case, sales_data.xlsx is assumed to be in the same folder as the Python script. The open method loads the workbook, and wb.sheets provides access to its sheets.

  1. Example with Full Path and Read-Only Mode:
    Here, we open a workbook using an absolute path and in read-only mode to safely read data without altering the file.
import xlwings as xw
# Specify the full path to the workbook
file_path = r'C:\Users\JohnDoe\Documents\financial_report.xlsx'
# Open in read-only mode
wb = xw.books.open(file_path, read_only=True)
# Access data from a specific cell
data = wb.sheets['Summary'].range('A1').value
print("Data from A1:", data)
# No need to save changes since it's read-only
wb.close()

This approach is ideal for scenarios where you need to extract information from a shared or sensitive workbook without risking modifications.

  1. Example in a Data Analysis Context:
    You can combine Open with other xlwings features to perform data analysis. For instance, open a workbook, read a range of data into a pandas DataFrame, and then visualize it.
import xlwings as xw
import pandas as pd
import matplotlib.pyplot as plt
# Open the workbook
wb = xw.books.open('survey_results.xlsx')
# Read data from a sheet into a DataFrame
sheet = wb.sheets['Responses']
df = sheet.range('A1').expand().options(pd.DataFrame, index=False, header=True).value
# Perform basic analysis (e.g., count responses by category)
category_counts = df['Category'].value_counts()
# Create a simple bar chart
category_counts.plot(kind='bar')
plt.title('Survey Responses by Category')
plt.show()
# Optionally, save the workbook with updates (if not read-only)
# wb.save()
wb.close()

How to use Workbook.Close in the xlwings API way

The Close member of the Workbook object in the xlwings API is used to close a specific Excel workbook. This action is essential for managing system resources and ensuring that changes are saved or discarded as intended. When you close a workbook, you can control whether to save any unsaved changes, specify a file path for saving, or even bypass alerts that might appear during the closing process. This functionality is particularly useful in automation scripts where multiple workbooks are processed sequentially, as it helps prevent memory leaks and keeps the Excel application running smoothly without unnecessary open files.

Syntax:
In xlwings, the Close method is called on a Book object (which represents a workbook). The basic syntax is as follows:

wb.close()

However, the method supports optional parameters to customize its behavior:

  • save_changes: A boolean value that determines whether to save changes before closing. If True, the workbook is saved; if False, changes are discarded. If omitted, Excel may prompt the user based on the workbook’s state.
  • route_workbook: This parameter is less commonly used in modern Excel versions and is typically set to False. It relates to routing workbooks in older workflows.
    The method does not return any value.

Parameters in Detail:

ParameterTypeDescriptionDefault Value
save_changesboolIf True, saves the workbook before closing. If False, discards changes. If not provided, Excel may show a prompt.None (Excel decides)
route_workbookboolUsed for routing in older Excel versions; generally set to False.False

Code Examples:
Here are practical examples of using the Close member in xlwings:

  1. Basic Close Without Saving:
    This example opens a workbook and closes it immediately without saving, which is useful for read-only operations.
import xlwings as xw
# Open an existing workbook
wb = xw.Book('example.xlsx')
# Perform some operations (e.g., read data)
data = wb.sheets['Sheet1'].range('A1').value
# Close the workbook without saving changes
wb.close(save_changes=False)
  1. Close and Save Changes:
    In this case, changes made to the workbook are saved automatically upon closing, streamlining the workflow.
import xlwings as xw
wb = xw.Book('report.xlsx')
# Modify the workbook (e.g., update a cell)
wb.sheets[0].range('B2').value = 'Updated Data'
# Close and save the changes
wb.close(save_changes=True)
  1. Close Multiple Workbooks in a Loop:
    This example demonstrates closing several workbooks in sequence, which is common in batch processing scripts.
import xlwings as xw
file_paths = ['data1.xlsx', 'data2.xlsx', 'data3.xlsx']
for path in file_paths:
    wb = xw.Book(path)
    # Process each workbook (e.g., aggregate data)
    print(f"Processed {path}")
# Close each workbook after processing, saving changes
wb.close(save_changes=True)
  1. Handling Prompts with Close:
    If you want to avoid Excel prompts when closing, ensure to set save_changes explicitly. Otherwise, Excel might interrupt automation with a dialog box.
import xlwings as xw
wb = xw.Book('temp.xlsx')
wb.sheets[0].range('A1').value = 'Test'
# Close and let Excel handle saving (may prompt if unsaved changes exist)
wb.close() # No save_changes specified; use with caution in automation

How to use Workbook.CheckOut in the xlwings API way

The CheckOut method of the Workbook object in Excel is used to check out a workbook from a server that is using SharePoint or a similar document management server. This functionality is essential in collaborative environments where multiple users need to work on the same file but with version control to prevent conflicts. By checking out a workbook, a user gains exclusive write access, ensuring that others cannot make changes until it is checked back in. This helps maintain data integrity and track revisions. In xlwings, this method can be accessed via the Workbook API, allowing Python scripts to programmatically manage workbook check-outs as part of automated workflows, such as in data analysis pipelines that involve shared resources.

Syntax in xlwings:
The CheckOut method is called on a Workbook object. The syntax is straightforward, as it does not require additional parameters in its basic form. However, it’s important to note that the workbook must be opened from a server location (e.g., a SharePoint URL) for this method to be applicable. If called on a local workbook, it may raise an error or have no effect.

In xlwings, the method is accessed as:

workbook.api.CheckOut()

Here, workbook refers to the xlwings Workbook object, and .api is used to access the underlying Excel object model. The CheckOut method does not take any arguments. It returns None upon successful execution. If the workbook is already checked out by another user or if there are network issues, an error may occur, which should be handled with try-except blocks in Python.

Example Usage:
Consider a scenario where an analyst needs to check out an Excel workbook from a SharePoint site to perform data updates without interference. The xlwings code below demonstrates how to open the workbook from a server path and check it out. Ensure that the path points to the server location and that you have the necessary permissions.

import xlwings as xw

# Open the workbook from a SharePoint or server location
server_path = r'https://yourcompany.sharepoint.com/sites/SharedDocuments/DataWorkbook.xlsx'
try:
    # Open the workbook in Excel (visible or background)
    wb = xw.Book(server_path)

    # Check out the workbook to gain exclusive write access
    wb.api.CheckOut()

    print("Workbook checked out successfully. You can now make changes.")

    # Perform data operations: e.g., update a cell with new data
    sheet = wb.sheets['Sheet1']
    sheet.range('A1').value = 'Updated by Python script'

    # Save changes (optional, but recommended before checking in)
    wb.save()

    # Note: To release the workbook for others, use CheckIn method later
    # wb.api.CheckIn(SaveChanges=True, Comments="Updated via xlwings")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Close the workbook if needed, but ensure to check in first in real scenarios
    if 'wb' in locals():
        wb.close()

How to use Workbook.CanCheckOut in the xlwings API way

The CanCheckOut member of the Workbook object in Excel’s object model is a read-only property that indicates whether a workbook stored on a Microsoft SharePoint server can be checked out to the local machine. This property is particularly useful in collaborative environments where multiple users may need to edit a shared workbook. By checking this property, a developer can determine if the workbook is available for exclusive editing before attempting a check-out operation, thus preventing potential errors or conflicts.

In xlwings, you can access the CanCheckOut property through the api property of a Book object, which provides direct access to the underlying Excel object model. The syntax for using this property is straightforward. Given an xlwings Book object, you can call the property as follows:

can_checkout_status = workbook.api.CanCheckOut

Here, workbook is an xlwings Book instance representing the open workbook. The api property exposes the native Excel VBA object model, allowing you to use the CanCheckOut property directly. The property returns a Boolean value: True if the workbook can be checked out from the server, and False otherwise. This check is essential before proceeding with the CheckOut method, which would otherwise throw an error if the workbook cannot be checked out.

For example, consider a scenario where you have a workbook opened from a SharePoint location. You can use the following code to verify its check-out status:

import xlwings as xw

# Open the workbook from a SharePoint path or a local path linked to SharePoint
wb_path = r'https://your-sharepoint-site.com/path/to/workbook.xlsx'
wb = xw.Book(wb_path)

# Check if the workbook can be checked out
if wb.api.CanCheckOut:
    print("The workbook can be checked out. Proceeding with check-out...")
    wb.api.CheckOut(wb_path) # Check out the workbook to the local machine
else:
    print("The workbook cannot be checked out at this time. It may already be checked out by another user or not stored on a server.")

In this example, the code first opens the workbook using xlwings. It then uses wb.api.CanCheckOut to determine if a check-out is possible. If it returns True, the code proceeds to call the CheckOut method, passing the workbook path as an argument to perform the check-out. If it returns False, a message is printed, indicating the workbook is unavailable for check-out, which helps avoid runtime errors.

Another practical use case is in automated scripts that manage document workflows. For instance, before performing any edits, you might want to ensure the workbook is checked out to prevent overwriting conflicts:

import xlwings as xw

# Assume the workbook is already open or referenced
wb = xw.books.active # Get the active workbook

# Verify check-out capability
if wb.api.CanCheckOut:
    try:
        wb.api.CheckOut(wb.fullname) # Attempt to check out using the workbook's full path
        print(f"Workbook '{wb.name}' has been successfully checked out.")
        # Perform edits here
        # wb.sheets[0].range('A1').value = 'Updated Data'
    except Exception as e:
        print(f"An error occurred during check-out: {e}")
else:
    print(f"Workbook '{wb.name}' is not available for check-out. Please check server status or user permissions.")

How to use Workbook.Add in the xlwings API way

The Add member of the Workbook object in the Excel object model is a method used to create a new workbook. In xlwings, which provides a powerful API to interact with Excel from Python, this functionality is accessed through the App class rather than directly from a Workbook instance. The App represents the Excel application itself, and its add() method creates a new workbook, returning a Book object (xlwings’ equivalent to a Workbook). This is essential for automating the generation of reports, dashboards, or any task requiring dynamic workbook creation.

Functionality:
The primary function is to launch a new, blank workbook in Excel. This new workbook becomes the active workbook and is added to the App.books collection. It provides a foundation for subsequent operations like adding data, creating charts, or applying formatting without needing a pre-existing file.

Syntax and Parameters:
In xlwings, the method is called on an App instance. The basic syntax is:

new_workbook = xw.App().add()

However, it is more common to use an existing application context. When you have an App object (e.g., app = xw.App() or when using xw.Book which creates an app implicitly), you call:

new_workbook = app.add()

The add() method does not take any parameters in xlwings. Its behavior is straightforward: it creates one new, empty workbook. This differs slightly from the native Excel VBA object model, where the Add method can accept a template parameter. In xlwings, to create a workbook from a template, you would typically use the Book constructor with a file path.

Code Examples:
Here are practical examples demonstrating the add() method.

  1. Creating a new workbook in a new Excel instance:
import xlwings as xw

# Start a new Excel application
app = xw.App()
# Add a new, blank workbook
new_book = app.add()
# Write data to the first cell of the active sheet
new_book.sheets[0].range('A1').value = "New Workbook Data"
# Save the workbook
new_book.save(r'C:\Reports\Report1.xlsx')
# Close the workbook and quit Excel
new_book.close()
app.quit()
  1. Adding multiple workbooks to an existing application instance:
import xlwings as xw

# Connect to a running instance or start a new one
app = xw.App(visible=True)
# Create the first new workbook
book1 = app.add()
book1.sheets[0].range('A1').value = "Workbook 1"
# Create a second new workbook
book2 = app.add()
book2.sheets[0].range('A1').value = "Workbook 2"
# At this point, two new workbooks are open in the same Excel application.
# ... perform other tasks ...
for book in app.books:
book.close()
app.quit()
  1. Using within a context manager (recommended for resource management):
import xlwings as xw

with xw.App() as app:
# The `add()` method works the same within the context
new_book = app.add()
new_book.sheets[0].range('A1').value = "Created in Context"
new_book.save('context_workbook.xlsx')
# The context manager automatically closes the book and quits the app on exit.

How to use Workbooks.Parent in the xlwings API way

The Parent property of the Workbooks object in Excel’s object model is a read-only property that returns the parent object for the specified collection. In the context of the Workbooks collection, the parent is the Excel Application object itself. This property is useful when you need to access application-level settings, methods, or properties from a workbook context, such as adjusting application settings or retrieving the application version. In xlwings, this property is accessible through the api property, which provides direct access to the underlying Excel object model, allowing for precise control and integration with Excel’s native features.

Functionality:
The primary function of the Parent property is to provide a reference to the Excel Application object that contains the Workbooks collection. This enables developers to perform operations at the application level, such as:

  • Changing global Excel settings (e.g., ScreenUpdating, Calculation).
  • Accessing other application-level collections like AddIns.
  • Retrieving application information (e.g., Version, UserName).

Syntax:
In xlwings, the syntax to access the Parent property of the Workbooks object is as follows:

app = xw.books.api.Parent
  • app: This variable will hold a reference to the Excel Application object.
  • xw.books: This refers to the Workbooks collection in xlwings.
  • .api: This provides the underlying COM object, exposing the native Excel object model.
  • .Parent: This is the property being called, returning the parent Application object.

No parameters are required for this property as it is read-only and does not accept arguments.

Code Examples:
Below are practical examples demonstrating the use of the Parent property in xlwings:

  1. Accessing Application Properties:
    This example shows how to retrieve the Excel application’s version and user name using the Parent property.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Get the Workbooks collection's parent (Application)
excel_app = xw.books.api.Parent

# Access application-level properties
version = excel_app.Version
user_name = excel_app.UserName

print(f"Excel Version: {version}")
print(f"Current User: {user_name}")
  1. Modifying Application Settings:
    This example illustrates how to toggle the ScreenUpdating property to improve performance during macro execution.
import xlwings as xw

# Start or connect to Excel
app = xw.App(visible=True)

# Access the parent Application from Workbooks
excel_app = xw.books.api.Parent

# Disable screen updating for faster execution
excel_app.ScreenUpdating = False

# Perform data operations (e.g., adding a new workbook)
wb = xw.books.add()
wb.sheets[0].range("A1").value = "Data loaded..."

# Re-enable screen updating
excel_app.ScreenUpdating = True

# Save and close
wb.save("output.xlsx")
wb.close()
app.quit()
  1. Iterating Through Open Workbooks:
    This example uses the Parent property to list all open workbooks by accessing the Workbooks collection from the Application object.
import xlwings as xw

# Ensure Excel is running
if not xw.apps:
    xw.App(visible=True)

# Get the Application object via Parent
excel_app = xw.books.api.Parent

# Loop through all workbooks in the application
for wb in excel_app.Workbooks:
    print(f"Workbook Name: {wb.Name}")

# This provides a direct way to manage workbooks at the application level.