Archive

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: True to enable screen updates (default), False to 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: True to show alerts, False to 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: True to make Excel visible, False to 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 the separators dictionary under the app object, rather than as a direct property like in VBA. This dictionary includes other separators like decimal separators as well. The new_separator parameter 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:

  1. 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.

  1. 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.

  1. 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.row and caller.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:

  1. 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'."
  1. 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, using caller to 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.
  1. Conditional Formatting Simulation
    A UDF that changes the calling cell’s font color based on its value, using caller to 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 the caller object 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.
  1. Creating a UDF That Logs Its Usage
    This example uses caller to 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:

  1. 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."
  1. 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
  1. 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
  1. 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 xlwings App class, 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 StartupPath property 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.

  1. 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.")
  1. 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()
  1. 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()

How to use Application.StandardFont in the xlwings API way

The Application.StandardFont property in Excel refers to the default font name used for new workbooks and worksheets. Through xlwings, this property can be accessed and modified to programmatically control the standard font setting across Excel sessions. This is particularly useful for ensuring consistency in document formatting or adapting the default appearance to corporate style guidelines without manual intervention.

Functionality
This property allows you to retrieve or set the name of the standard font as a string. When you change it, any new workbook created thereafter will use this font as the default for cell text. Note that existing workbooks are not automatically updated; the change applies prospectively. It affects the Excel application instance, making it a global setting.

Syntax in xlwings
In xlwings, you interact with this property via the app object, which represents the Excel Application. The syntax is straightforward:

  • To get the current standard font: app.api.StandardFont
  • To set a new standard font: app.api.StandardFont = "font_name"

Here, app is your xlwings App instance. The .api attribute provides direct access to the underlying Excel object model (through pywin32 on Windows or appscript on macOS). The StandardFont property expects a string value representing a valid font name installed on the system, such as “Calibri”, “Arial”, or “Times New Roman”. There are no additional parameters.

Code Examples
Below are practical examples demonstrating how to use the StandardFont property with xlwings.

Example 1: Retrieving the Current Standard Font

import xlwings as xw

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

# Get the current standard font name
current_font = app.api.StandardFont
print(f"The current standard font is: {current_font}")

Example 2: Setting a New Standard Font

import xlwings as xw

# Ensure Excel is running; start if necessary
app = xw.App(visible=True)

# Set the standard font to Arial
app.api.StandardFont = "Arial"
print("Standard font changed to Arial.")

# Create a new workbook to see the effect
wb = app.books.add()
ws = wb.sheets[0]
ws.range("A1").value = "This text should be in Arial."

# Save and close
wb.save("new_workbook.xlsx")
wb.close()
app.quit()

Example 3: Verifying the Change Across Sessions

import xlwings as xw

# First, set the standard font
app = xw.App(visible=False)
app.api.StandardFont = "Courier New"
app.quit()

# Restart Excel and check
app_new = xw.App(visible=False)
font_check = app_new.api.StandardFont
print(f"After restart, standard font is: {font_check}") # Should be "Courier New"
app_new.quit()

How to use Application.SpellingOptions in the xlwings API way

The SpellingOptions member of the Application object in Excel provides a collection of settings that control how the spelling checker operates. These options are accessible through the xlwings library, allowing Python scripts to programmatically adjust spelling preferences, such as ignoring words in uppercase, flagging repeated words, or setting the language dictionary for proofing. This is particularly useful for automating document review processes, ensuring consistency in spell-checking behavior across multiple workbooks, or integrating custom spelling rules into data preparation workflows.

In xlwings, the SpellingOptions member is accessed via the api property of the Application object, which exposes the underlying Excel object model. The syntax for referencing it is straightforward: app.api.SpellingOptions, where app is an instance of the xlwings Application. This returns a SpellingOptions object with various properties that can be read or set. Most properties are Boolean values (True/False) or enumerations corresponding to Excel constants. For example, to check if the spelling checker ignores words in uppercase, you would use app.api.SpellingOptions.IgnoreUppercase. To modify it, assign a new value like app.api.SpellingOptions.IgnoreUppercase = True. Key properties include:

  • IgnoreUppercase: Ignores words in all uppercase letters.
  • IgnoreMixedDigits: Ignores words containing numbers.
  • SuggestMainOnly: Suggests only main dictionary entries.
  • GermanPostReform: Uses German post-reform spelling rules.
  • ArabicModes: Sets the Arabic spelling mode (e.g., for text validation).
    These properties map directly to Excel’s VBA SpellingOptions members, and their values can be retrieved or updated to customize spell-checking behavior.

For instance, to configure the spelling checker to ignore uppercase words and mixed digits, you could write:

import xlwings as xw
app = xw.App(visible=False) # Start Excel in background
app.api.SpellingOptions.IgnoreUppercase = True
app.api.SpellingOptions.IgnoreMixedDigits = True
print(f"Ignore uppercase: {app.api.SpellingOptions.IgnoreUppercase}")
app.quit() # Close the application

Another example involves setting language-specific options, such as enabling German post-reform rules:

import xlwings as xw
app = xw.App(visible=True)
app.api.SpellingOptions.GermanPostReform = True
# Perform a spell check on the active sheet
app.api.ActiveSheet.CheckSpelling()
app.quit()

Additionally, you can loop through all SpellingOptions properties to audit current settings:

import xlwings as xw
app = xw.App(visible=False)
options = app.api.SpellingOptions
for prop in ['IgnoreUppercase', 'IgnoreMixedDigits', 'SuggestMainOnly']:
    value = getattr(options, prop)
    print(f"{prop}: {value}")
app.quit()