Blog
How to use Application.TransitionMenuKeyAction in the xlwings API way
The TransitionMenuKeyAction property of the Application object in Excel is a legacy feature primarily designed for compatibility with older Lotus 1-2-3 spreadsheet software. Its function is to control how Excel interprets the forward slash (/) key press when it is the first key entered into a cell. In Lotus 1-2-3, this key combination was used to activate the menu system. Excel can mimic this behavior for users transitioning from that environment, either by displaying the Excel menu bar or by simply inserting a forward slash character into the active cell.
Syntax in xlwings:
The property is accessed through the main app object, which represents the Excel Application. It can be both read and written.
app.transition_menu_key_action
This property accepts and returns an integer value (or a constant from the xlwings.constants enumeration) that specifies the desired action. The possible values are:
| Value | xlwings Constant | Description |
|---|---|---|
| 0 | xlExcelMenus (or None) | The forward slash key activates the Excel menu bar. |
| 1 | xlLotusHelp | The forward slash key simply enters a / character into the cell. |
Code Examples:
- Reading the Current Setting:
This example checks the current behavior of the/key and prints a corresponding message.
import xlwings as xw
from xlwings.constants import xlExcelMenus, xlLotusHelp
app = xw.apps.active
current_action = app.transition_menu_key_action
if current_action == xlExcelMenus:
print("The forward slash key currently activates the Excel menu bar.")
elif current_action == xlLotusHelp:
print("The forward slash key currently enters '/' into the cell.")
else:
print(f"Unknown setting value: {current_action}")
- Changing the Setting:
This example changes the behavior so that pressing/at the start of a cell entry will simply insert the character, not open menus.
import xlwings as xw
from xlwings.constants import xlLotusHelp
app = xw.apps.active
# Set the property to enter the slash character
app.transition_menu_key_action = xlLotusHelp
print("Transition menu key action set to 'xlLotusHelp'.")
How to use Application.TransitionMenuKey in the xlwings API way
The Application.TransitionMenuKey property in Excel is a legacy feature that controls the key used to switch between the Excel menu and the Lotus 1-2-3 navigation keys in older versions. In modern Excel, its practical use is limited, primarily serving for backward compatibility or in specific macro-driven environments where Lotus 1-2-3 keyboard navigation emulation is required. Through xlwings, you can access and manipulate this property to read or set the designated key, allowing for automation scripts that interact with this niche aspect of Excel’s application settings.
Functionality:
This property gets or sets a single-character String that represents the menu key for switching to Lotus 1-2-3 navigation. When set, pressing this key (often “/” by default) toggles the menu access mode. It is a remnant from the era when Excel provided a transition aid for users migrating from Lotus 1-2-3.
Syntax in xlwings:
The property is accessed through the xlwings App object, which corresponds to the Excel Application.
# To get the current key
current_key = xw.apps.active.api.TransitionMenuKey
# To set a new key
xw.apps.active.api.TransitionMenuKey = "/"
Here, xw.apps.active.api provides the raw COM API proxy to the Excel Application object. The TransitionMenuKey property is exposed directly through this interface. It accepts a String of length 1. Common values include “/” (forward slash) or another single character. Setting it to an empty string (“”) effectively disables the key.
Example Usage:
Below is a practical xlwings code example that demonstrates reading the current TransitionMenuKey, changing it, and then restoring the original value. This can be useful in a script that temporarily modifies Excel’s environment.
import xlwings as xw
# Connect to the active Excel instance
app = xw.apps.active
# Read and print the current TransitionMenuKey
original_key = app.api.TransitionMenuKey
print(f"The original transition menu key is: '{original_key}'")
# Set a new transition menu key (e.g., to "/" if not already)
new_key = "/"
app.api.TransitionMenuKey = new_key
print(f"Transition menu key changed to: '{new_key}'")
# Perform other automation tasks here...
# For demonstration, simulate a scenario where the key is used.
# Restore the original key
app.api.TransitionMenuKey = original_key
print(f"Transition menu key restored to: '{original_key}'")
# Optional: Disable the key entirely
app.api.TransitionMenuKey = ""
print("Transition menu key disabled (set to empty string).")
How to use Application.Top in the xlwings API way
The Application object in Excel’s object model represents the entire Excel application, and through xlwings’ API, we can control many high-level settings and behaviors. Here, we focus on some of its most frequently used members for automation and customization.
1. Application.ScreenUpdating
- Functionality: Controls whether screen updates occur while a macro runs. Turning it off can significantly speed up code execution by preventing the screen from refreshing.
- Syntax:
app.screen_updating = boolean_value boolean_value:Trueto enable screen updates (default),Falseto disable.- Example:
import xlwings as xw
app = xw.App(visible=False) # Start Excel in background
app.screen_updating = False # Disable updates
# Perform operations like writing large data
wb = app.books.add()
wb.sheets[0].range('A1').value = [[1, 2], [3, 4]]
app.screen_updating = True # Re-enable updates
wb.save('output.xlsx')
wb.close()
app.quit()
2. Application.Calculation
- Functionality: Sets the calculation mode for Excel, such as automatic, manual, or semi-automatic, which is useful when working with large workbooks to control when formulas recalc.
- Syntax:
app.calculation = mode_value mode_value: Can be'automatic','manual', or'semiautomatic'. In xlwings, these correspond to Excel’s constants.- Example:
import xlwings as xw
app = xw.App()
wb = app.books.open('data.xlsx')
app.calculation = 'manual' # Set to manual calculation
# Change values without triggering recalc
wb.sheets[0].range('B1').value = 100
app.calculate() # Manually trigger calculation
result = wb.sheets[0].range('C1').value # Get calculated result
print(result)
wb.close()
app.quit()
3. Application.DisplayAlerts
- Functionality: Determines whether Excel displays alert messages (e.g., save prompts). Disabling alerts allows for smoother automated processes.
- Syntax:
app.display_alerts = boolean_value boolean_value:Trueto show alerts,Falseto suppress them.- Example:
import xlwings as xw
app = xw.App()
app.display_alerts = False # Suppress alerts
wb = app.books.open('temp.xlsx')
wb.close() # No prompt to save changes
app.display_alerts = True # Restore alerts
app.quit()
4. Application.Visible
- Functionality: Controls the visibility of the Excel application window. Hiding Excel can be useful for running scripts in the background.
- Syntax:
app.visible = boolean_value boolean_value:Trueto make Excel visible,Falseto hide.- Example:
import xlwings as xw
app = xw.App(visible=False) # Start hidden
# Perform operations without showing UI
wb = app.books.add()
wb.sheets[0].range('A1').value = 'Hidden Process'
wb.save('hidden_output.xlsx')
app.visible = True # Show Excel to user
wb.close()
app.quit()
5. Application.Version
- Functionality: Returns the version number of Excel, which can be helpful for compatibility checks.
- Syntax:
app.version - This is a read-only property returning a string.
- Example:
import xlwings as xw
app = xw.App()
version = app.version
print(f"Excel version: {version}") # e.g., '16.0' for Office 2016
if version.startswith('16'):
print("Compatible with Office 2016+ features.")
app.quit()
How to use Application.ThousandsSeparator in the xlwings API way
The ThousandsSeparator property of the Application object in Excel is a global setting that controls the character used to separate thousands in numbers when formatting and displaying numerical data. This property is part of Excel’s internationalization features, allowing customization to match regional formatting standards. For instance, in many European countries, a period (.) is used as the thousands separator, while in English-speaking countries like the United States, a comma (,) is typically used. By accessing this property via xlwings, you can programmatically read or modify the thousands separator setting for the active Excel instance, which can be useful for ensuring consistent number formatting across different locales in automated reports or data processing scripts.
Syntax in xlwings:
In xlwings, you can access the ThousandsSeparator property through the app object, which represents the Excel application. The property is available as an attribute of the app object, and it can be both read and written. The syntax is straightforward:
- To get the current thousands separator:
separator = app.separators['thousands'] - To set a new thousands separator:
app.separators['thousands'] = new_separator
Note that in xlwings, the ThousandsSeparator is accessed via theseparatorsdictionary under theappobject, rather than as a direct property like in VBA. This dictionary includes other separators like decimal separators as well. Thenew_separatorparameter should be a string containing a single character (e.g., “,” or “.”), and it must be a valid separator character supported by Excel for the current system locale.
Code Examples:
Here are some practical examples using xlwings to work with the ThousandsSeparator property:
- Reading the current thousands separator:
import xlwings as xw
# Connect to the active Excel application
app = xw.apps.active
# Get the current thousands separator
current_separator = app.separators['thousands']
print(f"The current thousands separator is: '{current_separator}'")
This code snippet retrieves and prints the thousands separator currently set in Excel, which might output something like ',' for a comma.
- Changing the thousands separator:
import xlwings as xw
# Connect to the active Excel application
app = xw.apps.active
# Set the thousands separator to a period (common in some European formats)
app.separators['thousands'] = '.'
print("Thousands separator updated to period.")
After running this, Excel will use a period as the thousands separator for new number formatting, affecting how numbers are displayed in cells.
- Applying the thousands separator in a workbook:
import xlwings as xw
# Start a new Excel instance and open a workbook
app = xw.App()
workbook = app.books.open('example.xlsx')
sheet = workbook.sheets[0]
# Change the thousands separator to a space (less common but possible)
app.separators['thousands'] = ' '
# Format a cell with a number to use the new separator
sheet.range('A1').value = 1234567
sheet.range('A1').number_format = '#,##0'
# The displayed value in Excel will now show as "1 234 567" if formatting is applied
workbook.save()
app.quit()
How to use Application.ThisWorkbook in the xlwings API way
The Application.ThisWorkbook property in Excel’s object model is a crucial member that returns a Workbook object representing the workbook where the current macro code is running. In the context of xlwings, a powerful Python library for automating Excel, this property is accessed differently since xlwings primarily interacts with Excel from an external Python script rather than from within Excel’s VBA environment. Therefore, xlwings does not have a direct, one-to-one equivalent property named ThisWorkbook. Instead, the concept is inherently handled by the main Book object you are working with. When you use xlwings to automate Excel, the workbook you open or connect to is your de facto “ThisWorkbook.”
Functionality:
In xlwings, the primary object representing an Excel workbook is xw.Book. When you instantiate this object by opening a file or connecting to an open instance, it serves the same purpose as Application.ThisWorkbook in VBA—it is the active workbook context for your operations. This object allows you to access and manipulate all elements within that specific workbook, such as worksheets, ranges, charts, and its properties.
Syntax:
The xlwings API does not use a property chain like Application.ThisWorkbook. Instead, you start by creating or referencing a Book object. The basic syntax is:
import xlwings as xw
# To open a specific workbook (like referencing ThisWorkbook if it's the macro host)
wb = xw.Book('C:/Path/To/Your/Workbook.xlsx')
# To connect to the currently active workbook in Excel
wb = xw.books.active
Once you have the wb object, you can access its members, such as worksheets, ranges, and properties. For example, to get the name of the workbook, similar to ThisWorkbook.Name in VBA, you use:
wb_name = wb.name
The Book object in xlwings provides numerous methods and properties. Key ones include:
wb.sheets: Returns a collection of all worksheets.wb.activate(): Activates the workbook in Excel.wb.save(): Saves the workbook.wb.close(): Closes the workbook.
Example Usage:
Below is a practical example demonstrating how to use xlwings to perform tasks analogous to using Application.ThisWorkbook in VBA. This script opens a workbook, reads data from a specific range, performs a calculation, and writes the result back, all within the context of that workbook.
import xlwings as xw
# Open the workbook (this is your 'ThisWorkbook' in xlwings context)
wb = xw.Book('Financial_Report.xlsx')
# Access a specific worksheet within the workbook
sheet = wb.sheets['SalesData']
# Read data from a range (e.g., A1 to B10)
data_range = sheet.range('A1:B10')
data = data_range.value # This returns a list of lists
# Perform a simple calculation: sum all numeric values in the range
total_sales = sum(cell for row in data for cell in row if isinstance(cell, (int, float)))
# Write the result to a specific cell in the same workbook
sheet.range('D1').value = total_sales
# Add a comment to the cell with the result
sheet.range('D1').add_comment(f'Total sales calculated on {datetime.now().date()}')
# Save the workbook
wb.save()
# Optionally, close the workbook
# wb.close()
How to use Application.ThisCell in the xlwings API way
The Application.ThisCell property in the Excel object model provides a powerful way to reference the cell in which the user-defined function (UDF) is being called from within the function’s code. In xlwings, this functionality is primarily accessed when you are writing custom functions (UDFs) that are called from Excel cells. It allows your Python function to know exactly which cell invoked it, enabling dynamic references and context-aware calculations. This is especially useful for creating intelligent UDFs that can adapt based on their location in a worksheet.
Syntax in xlwings:
Within a Python function decorated as a UDF with @xw.func, you can access ThisCell through the caller argument provided by xlwings. The caller object represents the calling cell. The typical way to use it is:
import xlwings as xw
@xw.func
def my_udf():
caller = xw.Range('ThisCell') # Not directly correct in this context; see below.
However, the direct equivalent is achieved by using the caller parameter in the function signature. When xlwings calls your UDF, it can pass the calling range. The correct approach is:
@xw.func
def my_udf(caller):
# 'caller' is an xlwings Range object representing the cell where the UDF is entered.
cell_address = caller.address
sheet_name = caller.sheet.name
# You can now use caller to get or set properties of that cell.
Here, caller is a parameter that xlwings automatically provides when the function is called from Excel. It is an instance of xlwings.Range, representing the single cell where the UDF formula resides. You do not need to pass this argument manually from Excel; xlwings handles it. The caller gives you access to all properties and methods of the Range object, such as address, value, formula, or adjacent cells.
Key Parameters and Usage:
caller(xlwings.Range): The Range object for the calling cell. It is passed automatically by xlwings when the UDF is invoked from an Excel cell. You can inspect its properties:caller.address: Returns the address (e.g., “A1”).caller.value: Gets or sets the cell’s value.caller.sheet: Accesses the parent worksheet.caller.rowandcaller.column: Get the row and column numbers.
This mechanism is analogous to Excel’s Application.ThisCell in VBA, which returns a Range object for the cell containing the UDF. In xlwings, it enables UDFs to be context-sensitive.
Code Examples:
- Basic Example: Returning the Calling Cell’s Address
This UDF returns the address of the cell it is called from, demonstrating how to access the caller’s location.
import xlwings as xw
@xw.func
def get_cell_address(caller):
return f"The UDF is in cell {caller.address} on sheet '{caller.sheet.name}'."
# In Excel, if you enter =get_cell_address() in cell B5, it returns:
# "The UDF is in cell $B$5 on sheet 'Sheet1'."
- Dynamic Calculation Based on Adjacent Cells
This example shows a UDF that sums the values of cells directly to the left and above the calling cell, usingcallerto reference adjacent ranges.
@xw.func
def sum_adjacent(caller):
left_cell = caller.offset(0, -1) # Cell to the left
above_cell = caller.offset(-1, 0) # Cell above
# Ensure the referenced cells contain numbers; default to 0 if not.
left_value = left_cell.value if isinstance(left_cell.value, (int, float)) else 0
above_value = above_cell.value if isinstance(above_cell.value, (int, float)) else 0
return left_value + above_value
# If cell C3 contains =sum_adjacent(), it will add values from B3 and C2.
- Conditional Formatting Simulation
A UDF that changes the calling cell’s font color based on its value, usingcallerto modify properties. Note: UDFs typically should not modify other cells due to Excel’s calculation rules, but they can modify the calling cell’s properties in some contexts (though this is often limited; xlwings supports it via thecallerobject for formatting).
@xw.func
def highlight_if_positive(caller, value):
if value > 0:
caller.color = (0, 255, 0) # Green background
else:
caller.color = (255, 0, 0) # Red background
return value # Return the original value for display.
# In Excel, =highlight_if_positive(A1) will color the cell based on A1's value.
- Creating a UDF That Logs Its Usage
This example usescallerto record the time and location whenever the UDF is calculated, by writing to a separate log sheet.
import datetime
@xw.func
def logged_calculation(caller, input_value):
log_sheet = xw.Book.caller().sheets['Log']
next_row = log_sheet.range('A' + str(log_sheet.cells.last_cell.row)).end('up').row + 1
log_sheet.range(f'A{next_row}').value = datetime.datetime.now()
log_sheet.range(f'B{next_row}').value = caller.address
log_sheet.range(f'C{next_row}').value = input_value
return input_value * 2
# This UDF doubles the input and logs each call in a "Log" sheet.
How to use Application.TemplatesPath in the xlwings API way
In Excel, the Application object serves as the top-level object representing the entire Excel application. Among its many members, the TemplatesPath property is a read‑only property that returns the full path to the folder where Excel stores its template files. This is useful when you need to programmatically locate the default template directory, for example to save a custom template or to list available templates. In xlwings, you can access this property through the Application object, which is exposed via the app object when you have an active connection to Excel.
The xlwings API syntax for accessing the TemplatesPath property is straightforward. Since it is a property, you simply reference it without parentheses. The general format is:
app.api.TemplatesPath
Here, app is an instance of the xlwings App class, which corresponds to the Excel Application object. The .api attribute provides direct access to the underlying Excel object model, allowing you to call native Excel properties and methods. The TemplatesPath property returns a string representing the full directory path. No parameters are required because it is a read‑only property.
For example, if you want to retrieve the default templates path and print it, you would use the following code:
import xlwings as xw
# Connect to the active Excel instance or start a new one
app = xw.apps.active
# Get the TemplatesPath
templates_folder = app.api.TemplatesPath
print(f"The default templates path is: {templates_folder}")
This code snippet first imports xlwings and then connects to the currently active Excel application. By accessing app.api.TemplatesPath, it retrieves the path and prints it. The output might look like C:\Users\[Username]\AppData\Roaming\Microsoft\Templates\ on Windows or a corresponding path on macOS.
Another practical use case is to combine the TemplatesPath with other operations, such as saving a workbook as a template in the default location. For instance:
import xlwings as xw
import os
app = xw.apps.active
wb = app.books.active
# Get the templates path and define a new template file name
templates_path = app.api.TemplatesPath
new_template_name = "MyCustomTemplate.xltx"
full_path = os.path.join(templates_path, new_template_name)
# Save the active workbook as a template in the default folder
wb.save(full_path)
print(f"Template saved to: {full_path}")
How to use Application.StatusBar in the xlwings API way
The StatusBar property of the Application object in Excel is a useful feature for providing real-time feedback to users during lengthy operations, such as data processing, calculations, or macro execution. In xlwings, this functionality is accessible through the api property, which provides direct access to the underlying Excel object model. This allows developers to set custom messages, display progress indicators, or clear the status bar, enhancing the user experience in automated Excel tasks.
Functionality
The StatusBar property controls the text displayed in the status bar at the bottom of the Excel window. It can be used to show informative messages, progress updates (e.g., “Processing… 50% complete”), or temporary notifications. When set to False, it clears any custom message and restores Excel’s default status bar display, such as showing “Ready” or calculation status. This is particularly valuable in long-running scripts to keep users informed without interrupting the workflow.
Syntax
In xlwings, the StatusBar property is accessed via the Application object. The basic syntax is:
app = xw.apps.active # Get the active Excel application
app.api.StatusBar = "Your message here" # Set a custom message
To clear the custom message and revert to Excel’s default display:
app.api.StatusBar = False
The property is both readable and writable. You can retrieve the current status bar text by reading app.api.StatusBar, which returns a string if a custom message is set, or False if the default is active. Note that the StatusBar does not accept complex formatting; it only displays plain text. Parameters are not required for setting or clearing—simply assign a string or False as shown.
Code Examples
Here are practical examples of using the StatusBar property with xlwings:
- Setting a Custom Message: Display a notification during data processing.
import xlwings as xw
app = xw.apps.active
app.api.StatusBar = "Loading data... Please wait."
# Simulate a task, e.g., processing data
import time
time.sleep(2)
app.api.StatusBar = "Data loaded successfully."
- Showing Progress Updates: Implement a simple progress indicator in a loop.
import xlwings as xw
app = xw.apps.active
total_items = 100
for i in range(total_items):
progress = (i + 1) / total_items * 100
app.api.StatusBar = f"Processing... {progress:.1f}% complete"
# Simulate work, e.g., updating cells
time.sleep(0.1)
app.api.StatusBar = False # Clear after completion
- Clearing the Status Bar: Restore Excel’s default display after an operation.
import xlwings as xw
app = xw.apps.active
app.api.StatusBar = "Task in progress..."
# Perform some operations, e.g., formatting a range
sheet = app.books.active.sheets[0]
sheet.range("A1:A10").value = "Updated"
app.api.StatusBar = False # Revert to default status
- Reading the Current Status: Check if a custom message is set.
import xlwings as xw
app = xw.apps.active
app.api.StatusBar = "Calculating results..."
current_status = app.api.StatusBar
print(f"Status bar says: {current_status}") # Output: Status bar says: Calculating results...
How to use Application.StartupPath in the xlwings API way
The StartupPath property of the Application object in Excel’s object model is a read-only property that returns the complete path to the startup folder used by Microsoft Excel. This folder is where Excel looks for add-ins, templates, and other files when it starts. In xlwings, you can access this property through the api property of the App or Book objects, which provides a direct gateway to the underlying Excel object model. This is particularly useful for developers who need to programmatically determine the startup directory to manage or load resources that Excel uses during initialization.
Syntax in xlwings:
The property is accessed via the Application object. In xlwings, you typically start by creating an instance of the Excel application or referencing an existing one. The syntax is straightforward:
app = xw.App() # or use xw.apps.active for an existing instance
startup_path = app.api.StartupPath
app: An instance of the xlwingsAppclass, representing the Excel application.api: This attribute provides access to the native Excel object model (via pywin32 on Windows or appscript on macOS).StartupPath: The property name, which requires no parameters and returns a string containing the full path.
Key Points:
- The
StartupPathproperty is read-only; you cannot set it directly through xlwings or Excel’s object model to change the startup folder. Modifications to the startup path would typically involve Windows registry settings or Excel options. - The returned path is system-dependent and may vary based on the Excel version and installation. On Windows, it often points to a directory like
C:\Users\[Username]\AppData\Roaming\Microsoft\Excel\XLSTART. - This property is useful for automating tasks such as checking for the presence of specific add-ins, deploying custom templates, or logging startup configurations in scripts.
Example Code:
Here is a practical example demonstrating how to retrieve and use the StartupPath property in xlwings. This script launches Excel, gets the startup path, and prints it, then lists any files present in that directory:
import xlwings as xw
import os
# Launch Excel application
app = xw.App(visible=True)
# Access the StartupPath property
startup_path = app.api.StartupPath
print(f"Excel Startup Path: {startup_path}")
# Optional: List files in the startup directory (if it exists)
if os.path.exists(startup_path):
files = os.listdir(startup_path)
print("Files in startup directory:")
for file in files:
print(f" - {file}")
else:
print("Startup directory does not exist.")
# Close Excel
app.quit()
How to use Application.StandardFontSize in the xlwings API way
The StandardFontSize member of the Application object in Excel allows you to get or set the default font size, measured in points, that is used for new workbooks and standard text styles. This is a global setting within the Excel application instance, meaning it affects the entire environment, not just a specific workbook. By adjusting this property, you can standardize the default appearance of text across newly created documents without manually formatting each cell. This is particularly useful for maintaining corporate branding or ensuring consistency in report generation.
In xlwings, you access this property through the api property of the App object, which provides direct access to the underlying Excel object model. The property is available for both reading and writing.
Syntax:
# To get the current standard font size
current_size = app.api.StandardFontSize
# To set a new standard font size
app.api.StandardFontSize = new_size
- app: An instance of the xlwings App class representing the Excel application.
- current_size: The returned value is a floating-point number representing the font size in points (e.g., 11.0).
- new_size: A numeric value (integer or float) specifying the desired default font size in points. It must be a positive number, typically within the range supported by Excel (e.g., 1 to 409 points). Setting this property immediately changes the application’s default, but note that it does not retroactively alter existing workbooks; it only applies to new workbooks created thereafter.
Example Usage:
Here are practical xlwings code snippets demonstrating how to work with the StandardFontSize property.
- Retrieving the Current Standard Font Size:
import xlwings as xw
# Connect to the active Excel instance or start a new one
app = xw.apps.active # or xw.App() for a new instance
# Get the current standard font size
default_size = app.api.StandardFontSize
print(f"The current standard font size is {default_size} points.")
- Setting a New Standard Font Size:
import xlwings as xw
# Start a new Excel application
app = xw.App()
# Set the standard font size to 14 points
app.api.StandardFontSize = 14
# Create a new workbook to see the effect
wb = app.books.add()
ws = wb.sheets[0]
# The default font in cell A1 should now be 14 points
print(f"Standard font size set to {app.api.StandardFontSize} points.")
# Save and close
wb.save('new_workbook.xlsx')
wb.close()
app.quit()
- Modifying the Setting and Creating Multiple Workbooks:
import xlwings as xw
app = xw.App(visible=False) # Run in background
# Store the original setting for later restoration
original_size = app.api.StandardFontSize
print(f"Original standard font size: {original_size} points")
# Change to a larger font for emphasis
app.api.StandardFontSize = 16
# Generate two new workbooks with the updated default
for i in range(2):
wb = app.books.add()
ws = wb.sheets[0]
ws.range('A1').value = f"This text uses the new standard size of {app.api.StandardFontSize} points."
wb.save(f'report_{i+1}.xlsx')
wb.close()
# Restore the original setting
app.api.StandardFontSize = original_size
print(f"Restored to original size: {app.api.StandardFontSize} points")
app.quit()