Archive

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.

How to use Workbooks.Item in the xlwings API way

The Item member of the Workbooks object in Excel’s object model is a property used to access a specific workbook within the Workbooks collection. In xlwings, this functionality is typically accessed through the books property of the App object, which represents the collection of open workbooks. The Item property allows you to retrieve a workbook by its index number (position in the collection) or by its name (as a string). This is essential for programmatically manipulating specific workbooks when multiple workbooks are open, enabling you to set a workbook as the active object, read data, or perform other operations.

Syntax in xlwings:
While xlwings does not explicitly expose an Item method, the books collection behaves similarly. You can access a workbook using indexing or key-based lookup.

  • By index (1-based, like Excel VBA): app.books[index]
  • By name (workbook filename): app.books[name]

Parameters:

  • index: An integer representing the position of the workbook in the books collection. The index starts at 1 for the first workbook opened or referenced.
  • name: A string that matches the full name (including extension) of the workbook, such as “Data.xlsx”. If the workbook is saved, you can use the base name without the path if it’s unique among open workbooks.

Examples:

  1. Access by Index:
    Suppose you have two workbooks open: “Report.xlsx” (opened first) and “Analysis.xlsx” (opened second). To reference the first workbook:
import xlwings as xw
app = xw.apps.active # Get the active Excel application
first_workbook = app.books[0] # Index 0 in xlwings corresponds to VBA's Item(1)
print(first_workbook.name) # Output: Report.xlsx

Note: xlwings uses 0-based indexing for collections in Python, unlike VBA’s 1-based Item. So app.books[0] is equivalent to Workbooks.Item(1) in VBA.

  1. Access by Name:
    To directly access a workbook named “Financials.xlsx”:
import xlwings as xw
app = xw.apps.active
target_workbook = app.books['Financials.xlsx']
target_workbook.activate() # Make it the active workbook

If multiple workbooks have similar names, ensure you use the full filename. This method is case-insensitive on Windows but case-sensitive on macOS.

  1. Iterating Through Workbooks:
    You can loop through all open workbooks using the books collection, which internally utilizes the Item property:
import xlwings as xw
app = xw.apps.active
for wb in app.books:
    print(f"Workbook: {wb.name}, Sheets: {[sheet.name for sheet in wb.sheets]}")

This iterates over each workbook and prints its name along with sheet names, demonstrating how Item underpins collection access.

  1. Error Handling:
    When accessing by name, if the workbook isn’t open, xlwings raises a KeyError. You can handle this gracefully:
import xlwings as xw
app = xw.apps.active
try:
    wb = app.books['NonExistent.xlsx']
except KeyError:
    print("Workbook not found. Please check if it's open.")

How to use Workbooks.Creator in the xlwings API way

The Creator property of the Workbooks object in Excel’s object model is a read-only property that returns a Long value representing the creator code for the application that created the file. This is particularly useful for identifying the original application when dealing with files that may have been created in different versions of Excel or other spreadsheet programs. In xlwings, this property can be accessed through the api property, which provides direct access to the underlying Excel object model.

Functionality:
The Creator property helps in determining the application that originally created the workbook. It returns a four-character code (as a Long integer) that corresponds to the creator. For example, Microsoft Excel typically uses the code “XCEL”. This can be useful in scenarios where you need to verify file origins or handle compatibility issues.

Syntax:
In xlwings, the syntax to access the Creator property is:

workbook.api.Creator

Here, workbook refers to an xlwings Book object. The property does not take any parameters and returns a Long value.

Example:
Below is a practical example of how to use the Creator property in xlwings to check the creator of an open workbook. This code opens a workbook, retrieves the creator code, and prints it along with a descriptive message.

import xlwings as xw

# Open an existing workbook or connect to an open one
wb = xw.Book('example.xlsx') # Replace with your file path

# Access the Creator property via the api
creator_code = wb.api.Creator

# Convert the Long code to a readable string (optional)
# Typically, you might map known codes to application names
if creator_code == 1480803660: # This is 'XCEL' in decimal for Excel
    creator_name = "Microsoft Excel"
else:
    creator_name = "Unknown Application"

# Output the result
print(f"The workbook creator code is: {creator_code}")
print(f"This corresponds to: {creator_name}")

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

How to use Workbooks.Count in the xlwings API way

The Workbooks.Count property in xlwings is a direct mapping from the Excel Object Model’s Workbook.Count property under the Workbooks collection. It provides a simple yet powerful way to programmatically determine the number of currently open workbooks in an Excel instance. This is particularly useful in automation scripts where you need to check the state of the Excel application, iterate through all open workbooks, or ensure a specific number of workbooks are present before performing batch operations.

Functionality:
The primary function of Workbooks.Count is to return a Long integer representing the count of all open workbook files in Microsoft Excel. This includes workbooks that are visible, hidden, or add-ins. It is a read-only property, meaning you can retrieve its value but cannot set it directly to change the number of open workbooks.

Syntax and Parameters:
In xlwings, you access this property through the app object, which represents the Excel application. The syntax is straightforward:

count = app.books.count
  • app: This is the xlwings App instance, representing the Excel application. You typically obtain it using xw.apps (to get a running instance) or xw.App() (to create a new one).
  • books: This is the xlwings equivalent of the Excel Workbooks collection. It provides access to all open workbooks.
  • count: This is the property that returns the integer count. No parameters are required.

There are no parameters to specify, as count is a simple property. Its value is dynamically determined by the state of the Excel application at the moment of access.

Code Examples:

  1. Basic Retrieval of Count:
    This example connects to the active Excel instance and prints the number of open workbooks.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active
# Get the count of open workbooks
open_count = app.books.count
print(f"Number of open workbooks: {open_count}")
  1. Conditional Logic Based on Count:
    This script checks if there are any workbooks open. If none are open, it creates a new one; otherwise, it activates the first workbook.
import xlwings as xw

app = xw.apps.active
if app.books.count == 0:
    print("No workbooks open. Creating a new one.")
    new_wb = app.books.add()
else:
    print(f"{app.books.count} workbook(s) open.")
    first_wb = app.books[0] # Access the first workbook in the collection
    first_wb.activate()
  1. Iterating Through All Open Workbooks:
    This example uses the count to loop through each open workbook and print its name. Using app.books.count in the range() function ensures you iterate over the exact number of items.
import xlwings as xw

app = xw.apps.active
num_books = app.books.count
print(f"Iterating through {num_books} workbook(s):")
for i in range(num_books):
    wb = app.books[i]
    print(f" - Workbook {i+1}: {wb.name}")
  1. Monitoring Workbook State:
    In a more dynamic scenario, you might use the count in a loop to wait for a specific number of workbooks to be opened by a user.
import xlwings as xw
import time

app = xw.apps.active
print("Waiting for at least 2 workbooks to be open...")
while app.books.count < 2:
time.sleep(0.5) # Check every half second
print("Condition met! Proceeding with automation.")
# ... perform tasks requiring multiple workbooks

How to use Workbooks.Application in the xlwings API way

The Application member of the Workbooks object in the Excel object model represents the Excel application itself. In xlwings, this is typically accessed through the app property when you have a workbook or a specific object, but you can also directly reference the Excel application instance. The Application object provides a wide range of properties and methods to control the Excel environment, such as settings for calculation, screen updating, and accessing other top-level objects.

Functionality:
The Application member allows you to interact with the Excel application globally. Common uses include:

  • Controlling Excel settings (e.g., turning off screen updates for performance).
  • Accessing properties like the version of Excel or the user name.
  • Managing workbooks and windows at the application level.
  • Executing application-wide methods, such as calculating all open workbooks.

Syntax:
In xlwings, you typically start by connecting to an existing Excel instance or creating a new one. The Application is represented by the app object. For example:

import xlwings as xw

# Connect to an existing Excel instance or start a new one
app = xw.App(visible=True, add_book=False)

Once you have the app object, you can access its properties and methods. The general syntax for accessing the Application member via xlwings is:

  • app.property_name for properties (e.g., app.version to get the Excel version).
  • app.method_name(parameters) for methods (e.g., app.calculate() to recalculate all open workbooks).

Key parameters for methods often include optional arguments that control behavior. For example, in methods that involve calculations, you might specify the calculation type. Here’s a table for common Application properties and methods in xlwings:

Member Typexlwings API ExampleDescriptionParameters/Values
Propertyapp.versionReturns the Excel version as a string.None
Propertyapp.screen_updatingGets or sets whether screen updating is enabled (Boolean).Set to True or False to toggle.
Methodapp.calculate()Forces a recalculation of all open workbooks.No parameters required.
Methodapp.quit()Closes the Excel application.None, but ensure to save workbooks first.
Methodapp.activate()Activates the Excel application window.None

Examples:
Here are practical xlwings code examples using the Application member:

  1. Getting Excel Version and User Name:
import xlwings as xw

app = xw.App(visible=False) # Start Excel in the background
print(f"Excel Version: {app.version}")
print(f"User Name: {app.user_name}")
app.quit() # Close Excel
  1. Controlling Screen Updates for Performance:
import xlwings as xw

app = xw.App(visible=True)
app.screen_updating = False # Turn off screen updates
# Perform data operations (e.g., open workbooks, write data)
wb = app.books.add() # Add a new workbook
wb.sheets[0].range("A1").value = "Hello, World!"
app.screen_updating = True # Turn screen updates back on
wb.save("example.xlsx")
app.quit()
  1. Recalculating All Workbooks:
import xlwings as xw

app = xw.App(visible=True)
# Open multiple workbooks and perform calculations
wb1 = app.books.open("workbook1.xlsx")
wb2 = app.books.open("workbook2.xlsx")
# After making changes to formulas, recalculate
app.calculate() # Forces recalculation across all open workbooks
wb1.save()
wb2.save()
app.quit()
  1. Activating Excel and Managing Windows:
import xlwings as xw

app = xw.App(visible=True)
app.activate() # Brings Excel to the foreground
wb = app.books.add()
# Customize window state (e.g., maximize)
app.windows[0].window_state = 'maximized'
print(f"Number of open workbooks: {len(app.books)}")
app.quit()