Archive

How to use Application.ShowChartTipValues in the xlwings API way

In the Excel object model, the Application.ShowChartTipValues property is a member of the top-level Application object. This property controls whether chart tip values (also known as data labels or tooltips) are displayed when you hover the mouse pointer over a data point in a chart within Excel. When enabled, users can see the exact numeric value of a data point directly on the chart, enhancing data visualization and analysis. This setting applies globally to all open workbooks in the Excel instance.

In xlwings, you can access and manipulate this property through the api property of the App object, which provides a direct gateway to the underlying Excel Application object via the COM interface. The xlwings API call follows the pattern: app.api.ShowChartTipValues, where app is an instance of xlwings.App. This property is a Boolean value, meaning it can be set to True to enable chart tip values or False to disable them. You can also retrieve its current state to check if the feature is active.

The syntax for using ShowChartTipValues in xlwings is straightforward:

  • To get the current setting: current_setting = app.api.ShowChartTipValues
  • To set the setting: app.api.ShowChartTipValues = True or app.api.ShowChartTipValues = False

There are no parameters for this property, as it is a simple Boolean attribute. However, it’s important to note that changes made to this property affect the entire Excel application session. This means that all charts across all open workbooks will adhere to this setting until it is changed again or Excel is closed. It’s a useful feature for presentations or reports where you might want to temporarily hide or show data values for clarity.

Here is a practical xlwings API code example that demonstrates how to use the ShowChartTipValues property:

import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active if xw.apps.active else xw.App()

# Get the current state of ShowChartTipValues
current_state = app.api.ShowChartTipValues
print(f"Current ShowChartTipValues setting: {current_state}")

# Disable chart tip values
app.api.ShowChartTipValues = False
print("Chart tip values have been disabled.")

# Perform some chart-related operations, e.g., open a workbook with a chart
wb = app.books.open('example.xlsx')
chart = wb.sheets[0].charts[0] # Assuming the first chart on the first sheet
# At this point, hovering over chart data points will not show values

# Re-enable chart tip values
app.api.ShowChartTipValues = True
print("Chart tip values have been re-enabled.")

# Close the workbook without saving
wb.close()

# Optionally, reset to the original state if needed
app.api.ShowChartTipValues = current_state

# Quit the Excel application if it was started by this script
if not xw.apps.active:
app.quit()

How to use Application.ShowChartTipNames in the xlwings API way

The ShowChartTipNames property of the Application object in Excel is a setting that controls whether chart tip names are displayed. Chart tips are the small pop-up labels that appear when you hover the mouse pointer over a chart element, such as a data point, series, or axis title. These tips typically show the name and value of the element. When ShowChartTipNames is set to True, these names are included in the tooltip. When set to False, only the values are shown, if applicable. This property is part of a group of settings that manage on-screen feedback and can be useful for creating cleaner visual presentations or for users who are already familiar with the chart’s data structure and do not require the additional descriptive text.

In the xlwings library, which provides a Pythonic interface to automate and interact with Excel, you access this property through the Application object. The syntax is straightforward, as it is a simple property getter and setter. The property expects a Boolean value (True or False).

xlwings API Syntax:

app = xw.App() # Get the active or a new Excel application instance
# To get the current setting
current_setting = app.api.ShowChartTipNames
# To set the property
app.api.ShowChartTipNames = True # or False

Here, app.api provides direct access to the underlying Excel VBA object model. The ShowChartTipNames property does not take any arguments; it is simply read or written to.

Code Example:
The following example demonstrates how to toggle the ShowChartTipNames setting and verify its state. This can be integrated into a larger script that prepares an Excel environment for a specific reporting task, ensuring that chart tooltips conform to a desired standard.

import xlwings as xw

# Connect to the active Excel instance
with xw.App(visible=True) as app:
# Get the current setting and print it
original_setting = app.api.ShowChartTipNames
print(f"Original ShowChartTipNames setting: {original_setting}")

# Disable the display of names in chart tips
app.api.ShowChartTipNames = False
print("ShowChartTipNames has been set to False. Chart tooltips will now only show values.")

# For demonstration, create a simple chart to see the effect
wb = app.books.add()
sheet = wb.sheets[0]
# Add some sample data
sheet.range('A1').value = [['Category', 'Value'],
['A', 10],
['B', 20],
['C', 15]]
# Create a chart
chart = sheet.charts.add()
chart.set_source_data(sheet.range('A1').expand())
chart.chart_type = 'column_clustered'
chart.api[1].HasTitle = True
chart.api[1].ChartTitle.Text = "Sample Chart"

# Pause to allow user to hover over chart and observe tooltips
input("Hover over a column in the chart. The tooltip should show only the value (e.g., '20'). Press Enter to continue...")

# Re-enable the display of names
app.api.ShowChartTipNames = True
print("ShowChartTipNames has been restored to True. Tooltips will now show names and values.")

input("Hover over a column again. The tooltip should now show both name and value (e.g., 'B: 20'). Press Enter to exit...")

# Optionally, restore the original setting before closing
app.api.ShowChartTipNames = original_setting
wb.close()

How to use Application.SheetsInNewWorkbook in the xlwings API way

The SheetsInNewWorkbook property of the Application object in Excel specifies the number of worksheets that are automatically included when a new workbook is created. This setting is a global option within the Excel application instance, allowing users or automation scripts to define a default sheet count, which can improve efficiency by avoiding the need to manually add sheets after workbook creation. In xlwings, this property is accessed through the Application object, providing a programmatic way to both retrieve and modify this default value.

Functionality:
The primary function is to control the default number of worksheets in new workbooks. This is particularly useful in automation scenarios where a consistent starting structure is required, or when preparing templates that need multiple sheets by default.

Syntax:

# To get the current setting
current_sheet_count = xw.apps[0].api.SheetsInNewWorkbook

# To set a new value
xw.apps[0].api.SheetsInNewWorkbook = new_count
  • xw.apps[0]: Represents the first (or a specific) Excel application instance controlled by xlwings. Use xw.apps.active for the active instance if multiple are open.
  • .api: Provides direct access to the underlying Excel object model (the COM API).
  • SheetsInNewWorkbook: The property being accessed. It expects an integer value.

Parameter/Value Details:

  • Type: Read/Write Property (Integer).
  • Value Range: The number must be an integer between 1 and 255, inclusive. Excel enforces these limits.
  • Default: Typically 1 in a standard Excel installation.
  • Persistence: This is an application-level setting in the current session. It is not permanently saved between Excel sessions unless configured within Excel’s options or set via a macro that runs on startup.

Code Examples:

  1. Retrieving the Current Default:
import xlwings as xw

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

# Get the current default number of sheets
default_sheets = app.api.SheetsInNewWorkbook
print(f"New workbooks currently start with {default_sheets} sheet(s).")
# Output example: New workbooks currently start with 1 sheet(s).
  1. Changing the Default and Creating a Workbook:
import xlwings as xw

app = xw.apps.active

# Set the default to 3 worksheets
app.api.SheetsInNewWorkbook = 3

# Create a new workbook. It will now contain 3 worksheets automatically.
new_wb = app.books.add()
print(f"New workbook has {len(new_wb.sheets)} sheets.")
# Output: New workbook has 3 sheets.

# List the sheet names
for sheet in new_wb.sheets:
print(sheet.name)
# Output: Sheet1, Sheet2, Sheet3
  1. Resetting to the Standard Default:
import xlwings as xw

app = xw.apps.active
# Reset to the common default of 1 sheet
app.api.SheetsInNewWorkbook = 1

How to use Application.Sheets in the xlwings API way

The Application.Sheets property in Excel’s object model provides a collection of all sheets within the open workbook, encompassing both worksheets and chart sheets. In xlwings, this is accessed via the app object, which represents the Excel application instance. The primary function is to retrieve a list or a specific sheet, enabling operations across multiple sheets or referencing sheets by name or index. This is essential for automating tasks that involve iterating through all sheets, checking their properties, or performing bulk operations.

Syntax in xlwings:
The property is accessed as app.sheets. It returns a Sheets collection object. To reference a specific sheet, you can use indexing or a sheet name.

  • app.sheets: Returns the collection of all sheets.
  • app.sheets[index]: Returns the sheet at the specified index (1-based).
  • app.sheets[name]: Returns the sheet with the given name.

Parameters:

  • index: An integer representing the sheet’s position in the workbook (starting from 1). For example, app.sheets[1] refers to the first sheet.
  • name: A string representing the exact name of the sheet, such as app.sheets["Sheet1"].

Code Examples:

  1. Iterate through all sheets and print names:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
for sheet in app.sheets:
    print(sheet.name)
wb.close()
app.quit()
  1. Access a specific sheet by name and modify a cell:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
target_sheet = app.sheets["DataSheet"]
target_sheet.range("A1").value = "Updated Value"
wb.save()
wb.close()
app.quit()
  1. Count the number of sheets and check types:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
sheet_count = len(app.sheets)
print(f"Total sheets: {sheet_count}")
# To check if a sheet is a worksheet (vs. chart sheet), use its type property
for sheet in app.sheets:
if sheet.type == 'chart':
    print(f"{sheet.name} is a chart sheet.")
else:
    print(f"{sheet.name} is a worksheet.")
wb.close()
app.quit()
  1. Add a new sheet and rename it using the collection:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
new_sheet = wb.sheets.add()
new_sheet.name = "Analysis"
# Access via app.sheets to confirm
print("Sheet names:", [s.name for s in app.sheets])
wb.save()
wb.close()
app.quit()

How to use Application.SensitivityLabelPolicy in the xlwings API way

The SensitivityLabelPolicy member of the Application object in Excel refers to a feature related to Microsoft Information Protection (MIP) sensitivity labels. These labels are used to classify and protect sensitive data within Office documents by applying encryption, watermarks, or access restrictions based on organizational policies. In xlwings, you can interact with this functionality to retrieve or set sensitivity label information for an Excel workbook programmatically, enabling automation of compliance and security tasks directly from Python.

Functionality
The SensitivityLabelPolicy provides access to the sensitivity label assigned to the active workbook. It allows you to get the current label’s details, such as its name, ID, and protection settings, or to apply a new label. This is particularly useful in enterprise environments where documents must adhere to data governance standards. Through xlwings, you can integrate these capabilities into larger data processing workflows, ensuring that workbooks are automatically classified according to predefined policies without manual intervention.

Syntax
In xlwings, you access the SensitivityLabelPolicy via the Application object. The typical syntax is:

import xlwings as xw
app = xw.App(visible=False) # Or use xw.apps.active for an existing instance
sensitivity_label = app.api.ActiveWorkbook.SensitivityLabel.Policy

Here, app.api provides the underlying COM object for Excel’s Application, allowing direct access to the VBA object model. The SensitivityLabel.Policy returns an object representing the current sensitivity label policy. To get specific properties, you can use methods like GetLabel or SetLabel, but note that the exact properties and methods depend on Excel’s object model and may require exploration via dir() or Excel’s VBA documentation. Common properties include:

  • Name: The display name of the sensitivity label.
  • Id: A unique identifier for the label.
  • IsEnabled: Indicates if the label is active (Boolean).
    Parameters for methods like SetLabel typically include the label ID or name, and sometimes additional settings like protection options. Refer to Microsoft’s official documentation for detailed parameter lists, as they can vary with Excel versions.

Example
Below is a practical xlwings code example that retrieves and sets a sensitivity label. This assumes you have an Excel workbook open with sensitivity labels configured in your organization.

import xlwings as xw

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

# Access the SensitivityLabelPolicy
policy = wb.api.SensitivityLabel.Policy

# Get current label information
try:
    label_info = policy.GetLabel()
    print(f"Current Sensitivity Label: {label_info.Name}")
    print(f"Label ID: {label_info.Id}")
except Exception as e:
    print(f"No label applied or error: {e}")

# Set a new sensitivity label (replace 'Your-Label-ID' with an actual ID)
# Note: Setting labels may require specific permissions and label IDs from your organization.
new_label_id = "Your-Label-ID" # Example ID; obtain from your MIP configuration
try:
    policy.SetLabel(new_label_id, "Set by xlwings")
    print("Sensitivity label updated successfully.")
except Exception as e:
    print(f"Failed to set label: {e}")

# Save and close
wb.save()
app.quit()

How to use Application.Selection in the xlwings API way

The Application.Selection member in the Excel object model is a powerful property that returns the currently selected object in the active window of the Excel application. This could be a Range, a Chart, a Shape, or any other selectable object. In xlwings, this property is accessed via the api property, which provides direct access to the underlying COM object model. It is particularly useful for writing macros or scripts that interact dynamically with the user’s current selection, enabling context-sensitive operations without hardcoding specific cell references or object names.

Functionality:
The primary function is to retrieve the object that is currently selected by the user in the Excel interface. This allows your xlwings script to perform operations on whatever the user has highlighted, such as reading data from a selected range, formatting it, or manipulating a selected chart. It enhances interactivity and flexibility in automation scripts.

Syntax:
In xlwings, you access this property through the Application object. The general syntax is:

selected_object = xw.apps[0].api.Selection
  • xw.apps[0]: This refers to the first (or typically the active) Excel application instance. You can use xw.apps.active if you have a specific instance active.
  • .api: This is the gateway to the native Excel object model (via COM).
  • .Selection: This property returns a COM object representing the current selection. Its type varies based on what is selected.

To work with the returned object effectively, you often need to check its type or convert it to an xlwings object. For example, if a Range is selected, you can wrap it with xw.Range for easier manipulation within xlwings.

Examples:
Here are several xlwings API code instances demonstrating the use of Application.Selection:

  1. Getting the Address of a Selected Range:
    This example retrieves the address of the currently selected cells and prints it.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active
# Get the current selection
selection = app.api.Selection
# Check if it's a Range (to avoid errors)
if selection.Type == 8: # 8 corresponds to xlRange in Excel constants
    range_address = selection.Address
    print(f"Selected range address: {range_address}")
  1. Reading Values from a Selected Range:
    This reads the values from the selected range and converts them into a list of lists using xlwings.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
if hasattr(selection, 'Value'): # Check if it has a Value property (like Range)
    # Wrap the COM Range with xlwings Range for .value property
    xl_range = xw.Range(selection)
    data = xl_range.value
    print(f"Selected data: {data}")
  1. Formatting the Selected Range:
    This changes the interior color of the selected cells to yellow.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
if selection.Type == 8:
    selection.Interior.Color = 65535 # Yellow color in RGB
  1. Working with a Selected Chart:
    If a chart is selected, this example changes its title.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
# Check if it's a Chart (Type 3 for xlChart)
if selection.Type == 3:
    selection.ChartTitle.Text = "Updated Chart Title via xlwings"
  1. Handling Multiple Selection Types:
    A more robust example that handles different selection types gracefully.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
selection_type = selection.Type

if selection_type == 8: # Range
    print(f"Range selected: {selection.Address}")
elif selection_type == 3: # Chart
    print("A chart is selected.")
elif selection_type == 4: # Shape
    print("A shape is selected.")
else:
    print(f"Other selection type: {selection_type}")

How to use Application.ScreenUpdating in the xlwings API way

The ScreenUpdating property of the Application object in Excel is a crucial tool for enhancing performance and user experience when automating tasks via xlwings. This property controls whether the Excel screen refreshes during the execution of VBA or, in this case, Python code. By setting ScreenUpdating to False, you can significantly speed up macros or scripts that perform extensive operations, such as writing large datasets, formatting numerous cells, or iterating through many worksheets. This prevents the screen from flickering and updating with each change, which not only improves efficiency but also provides a smoother, more professional appearance. Once the operations are complete, it is essential to set ScreenUpdating back to True to ensure the interface updates correctly and remains responsive for the user.

In xlwings, the ScreenUpdating member is accessed through the App object, which represents the Excel application. The property is a Boolean value that can be both read and written. The syntax for using it is straightforward: you reference the App instance and set or get the screen_updating attribute. Note that xlwings uses snake_case for most property names, aligning with Python conventions, so ScreenUpdating becomes screen_updating. The property accepts True or False values. When set to False, Excel stops updating the display until it is set back to True. It is good practice to handle this with error handling (e.g., try-finally blocks) to ensure the property is reset even if an error occurs during execution.

Here is a basic example of using ScreenUpdating with xlwings:

import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active

# Disable screen updating to improve performance
app.screen_updating = False

try:
    # Perform intensive operations, e.g., writing data to multiple sheets
    wb = app.books.active
    sheet = wb.sheets[0]
    for row in range(1, 1001):
        for col in range(1, 11):
            sheet.range((row, col)).value = f"Data{row}_{col}"
            # Additional operations like formatting can be added here
finally:
    # Re-enable screen updating regardless of errors
    app.screen_updating = True
    print("Screen updating has been re-enabled.")

Another common scenario involves toggling ScreenUpdating during data processing across multiple workbooks:

import xlwings as xw

# Start a new Excel instance (if not already open)
app = xw.App(visible=True) # Set visible=False for background operations

# Turn off screen updates
app.screen_updating = False

# Open a workbook and manipulate data
wb = app.books.open('example.xlsx')
sheet = wb.sheets['Sheet1']
# Example: Clear and repopulate a range
sheet.range('A1:D100').clear()
new_data = [[i * j for j in range(1, 5)] for i in range(1, 101)]
sheet.range('A1').value = new_data

# Save and close
wb.save()
wb.close()

# Re-enable updates
app.screen_updating = True
app.quit() # Close the Excel application

How to use Application.RTD in the xlwings API way

The Application.RTD property in Excel, accessed via the xlwings API, provides a powerful interface for working with Real-Time Data (RTD) servers. RTD enables Excel to receive live, continuously updated data from external sources, such as financial market feeds, sensor data, or custom server applications, without manual refreshes. This functionality is essential for building dynamic dashboards and monitoring systems directly within Excel workbooks.

Functionality
The primary purpose of the RTD property is to instantiate an IRTDUpdateEvent object. This object acts as the core event handler for the RTD server communication within Excel. It manages the update notifications, telling Excel when new data is available from the server. Through xlwings, developers can integrate Python-based logic to act as or interact with RTD servers, enabling real-time data processing and visualization directly from Python scripts.

Syntax and Parameters
In xlwings, you access this property through the Application object. The typical call pattern is:

import xlwings as xw
rtd_event = xw.apps.active.api.RTD

Here, rtd_event becomes a COM object representing Excel’s IRTDUpdateEvent interface. The key method of this interface is UpdateNotify(), which you would call from your RTD server code to signal Excel that fresh data is ready. The RTD property itself does not take parameters; its value is the event object.

Example: Simulating an RTD Update Trigger
The following xlwings code snippet demonstrates how to acquire the RTD event object and use it to manually trigger a data update notification in Excel. This is useful when you have a Python script acting as a data source.

import xlwings as xw
import time

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

# Access the RTD UpdateEvent object
rtd_update_event = app.api.RTD

# Simulate a background data-fetching loop
print("RTD server simulation started. Updates will be triggered every 5 seconds.")
try:
    while True:
        # ... (Your code here would fetch new real-time data)
        # Notify Excel that new data is available for any RTD-linked cells
        rtd_update_event.UpdateNotify()
        print(f"Update notification sent at {time.strftime('%H:%M:%S')}")
        time.sleep(5)
except KeyboardInterrupt:
    print("RTD update simulation stopped.")

How to use Application.Rows in the xlwings API way

The Application.Rows property in Excel’s object model is a powerful feature that, when accessed through the xlwings API, provides a convenient way to reference the entire collection of rows in the active Excel application’s window. This property returns a Range object representing all rows on the active worksheet, which can be manipulated for formatting, data operations, or analysis. In xlwings, this is accessed via the app object, which represents the Excel Application.

Functionality
Primarily, Application.Rows is used to obtain a reference to every row in the active sheet. This is useful for applying uniform formatting (like row height), performing bulk operations (such as hiding or unhiding all rows), or quickly counting the total number of rows available. It serves as a shortcut instead of specifying a range like A1:XFD1048576 in modern Excel. When combined with other Range properties and methods in xlwings, it enables efficient worksheet management.

Syntax
The xlwings API call to access this property is straightforward:

rows_range = app.api.Rows

Here, app is your xlwings App instance (connected to Excel). The .api attribute provides direct access to the underlying Excel object model. The Rows property does not take any parameters. The returned rows_range is a xlwings Range object (wrapping the Excel Range), which you can then use with standard xlwings methods or further drill into the raw API via .api.

Code Examples

  1. Setting Uniform Row Height:
import xlwings as xw
app = xw.apps.active # Get the active Excel application
all_rows = app.api.Rows # Access all rows
all_rows.row_height = 20 # Set every row's height to 20 points
  1. Hiding All Rows and Then Showing Them:
import xlwings as xw
app = xw.apps.active
rows = app.api.Rows
rows.hidden = True # Hide every row in the active sheet
# ... some operations ...
rows.hidden = False # Unhide all rows
  1. Counting Total Rows in the Sheet:
import xlwings as xw
app = xw.apps.active
total_rows = app.api.Rows.count # Returns 1048576 for .xlsx files
print(f"Total rows in the sheet: {total_rows}")
  1. Applying Formatting to All Rows:
import xlwings as xw
app = xw.apps.active
rows = app.api.Rows
rows.api.Font.bold = True # Make text in all rows bold via the raw API
rows.api.Interior.color = (220, 230, 241) # Set a light blue fill color

How to use Application.RollZoom in the xlwings API way

The Application.RollZoom property in Excel is a read-write Boolean property that controls whether scrolling with the IntelliMouse (or similar wheel mouse) zooms the worksheet instead of scrolling through it. When set to True, rolling the mouse wheel changes the zoom level of the active window. When set to False (the default), rolling the mouse wheel scrolls the worksheet up or down. This property is part of the Excel Application object, which represents the entire Excel application. In xlwings, you can access and manipulate this property through the app object, which corresponds to the Excel Application.

Functionality:
The primary function of RollZoom is to toggle the mouse wheel behavior between zooming and scrolling. This can enhance user experience when navigating large or detailed worksheets, as zooming can provide a better view of data without changing the visible range through scrolling.

Syntax in xlwings:
In xlwings, you access the Application object via the app property of a Book or directly through xw.apps. The RollZoom property is exposed as an attribute. The syntax is straightforward:

import xlwings as xw

# Get the current Excel application instance
app = xw.apps.active # or xw.App() for a new instance

# Get the current RollZoom setting
current_setting = app.api.RollZoom

# Set the RollZoom property
app.api.RollZoom = True # Enable zoom with mouse wheel
app.api.RollZoom = False # Enable scrolling with mouse wheel (default)

Note: app.api provides direct access to the underlying Excel object model. The RollZoom property is a Boolean, so it accepts True or False values.

Parameters:
This property does not have parameters in the traditional sense; it is a simple Boolean property. However, it affects the entire Excel application session, meaning the setting applies to all open workbooks and windows until changed. There is no direct method to specify a particular window or sheet; the property is global for the application instance.

Code Examples:

  1. Check and Toggle RollZoom Setting:
    This example checks the current RollZoom setting and toggles it, then prints a message to confirm the change.
import xlwings as xw

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

# Check current setting
if app.api.RollZoom:
    print("RollZoom is currently enabled (mouse wheel zooms).")
else:
    print("RollZoom is currently disabled (mouse wheel scrolls).")

# Toggle the setting
app.api.RollZoom = not app.api.RollZoom

# Verify the change
new_setting = "enabled" if app.api.RollZoom else "disabled"
print(f"RollZoom is now {new_setting}.")
  1. Temporarily Enable Zoom for Data Review:
    In this example, RollZoom is temporarily set to True to allow zooming during a data review process, then restored to its original state afterward.
import xlwings as xw

app = xw.apps.active
original_setting = app.api.RollZoom # Save the original setting

try:
    # Enable zoom for detailed data inspection
    app.api.RollZoom = True
    print("Zoom with mouse wheel is now active. Review your data.")

    # Simulate a pause or user interaction (e.g., input prompt)
    input("Press Enter after reviewing data to revert to original setting...")

finally:
    # Restore the original setting
    app.api.RollZoom = original_setting
    status = "enabled" if original_setting else "disabled"
    print(f"RollZoom has been restored to {status}.")
  1. Integrate with Workbook Operations:
    This example demonstrates setting RollZoom when opening a new workbook for a specific task, such as creating a chart, where zooming might be beneficial.
import xlwings as xw

# Start a new Excel instance (or use an existing one)
app = xw.App(visible=True)
app.api.RollZoom = True # Enable zoom for this session

# Add a new workbook and perform operations
wb = app.books.add()
sheet = wb.sheets[0]
sheet.range("A1").value = [[1, 2], [3, 4]] # Sample data

# Create a chart (zooming can help view chart details)
chart = sheet.charts.add()
chart.set_source_data(sheet.range("A1").expand())

print("Workbook created with RollZoom enabled. Use mouse wheel to zoom.")

# Keep the workbook open for user interaction
input("Press Enter to close and exit...")
wb.close()
app.quit()