Archive

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()

How to use Application.Speech in the xlwings API way

The Speech member of the Application object in Excel’s object model provides access to text-to-speech functionality, allowing developers to programmatically control speech playback of cell contents. This can be particularly useful for accessibility features, data verification by auditory feedback, or creating interactive tutorials. In xlwings, this functionality is exposed through the api property, which grants direct access to the underlying Excel VBA object model, enabling the use of the Speech object’s methods and properties.

Functionality:
The Speech object primarily controls the speech engine’s behavior, including speaking cell contents, managing speech playback (like pausing or resuming), and adjusting speech properties such as direction (by rows or columns) and speaking order. It allows for dynamic auditory output from spreadsheet data.

Syntax and Parameters:
In xlwings, the Speech member is accessed via app.api.Speech, where app is an instance of xlwings.App. Key methods include:

  • Speak(text, speakAsync, speakXML, purge): Speaks the specified text.
  • text: A string representing the text to be spoken.
  • speakAsync: A boolean; True for asynchronous speech (allows code to continue running), False for synchronous (code waits until speech finishes).
  • speakXML: A boolean; if True, interprets text as XML for speech synthesis control.
  • purge: A boolean; if True, purges any pending speech before speaking.
  • Properties like SpeakCellOnEnter: A boolean property that controls whether Excel speaks the cell contents when the Enter key is pressed. It can be set or retrieved.

Code Examples:
Here are practical examples using xlwings to demonstrate the Speech functionality:

  1. Speak a Specific Text Asynchronously:
import xlwings as xw
app = xw.App(visible=True)
# Speak "Hello from Excel" without blocking code execution
app.api.Speech.Speak("Hello from Excel", speakAsync=True)
app.quit()
  1. Enable Speaking Cell on Enter:
import xlwings as xw
app = xw.App(visible=True)
workbook = app.books.open('example.xlsx')
# Turn on speech when Enter is pressed in cells
app.api.Speech.SpeakCellOnEnter = True
# Now, when a user presses Enter after editing a cell, its content will be spoken
workbook.save()
app.quit()
  1. Speak Cell Contents Programmatically:
import xlwings as xw
app = xw.App(visible=True)
workbook = app.books.open('data.xlsx')
sheet = workbook.sheets['Sheet1']
# Get the value from cell A1 and speak it synchronously
cell_value = sheet.range('A1').value
app.api.Speech.Speak(str(cell_value), speakAsync=False)
app.quit()

How to use Application.SmartArtQuickStyles in the xlwings API way

The SmartArtQuickStyles member of the Application object in Excel refers to a collection that represents the set of SmartArt quick styles available within the application. In the context of xlwings, which provides a Pythonic interface to automate Excel, this collection can be accessed to retrieve information about or apply predefined style formats to SmartArt graphics in a workbook. This is particularly useful for programmatically enhancing the visual appeal of SmartArt diagrams, such as organizational charts or process flows, by applying consistent and professional styling without manual intervention.

Functionality:
The primary function is to enumerate and possibly apply the quick styles to SmartArt objects. Each quick style in the collection defines a combination of fills, lines, and effects that can be applied to a SmartArt graphic to change its overall appearance. Through xlwings, you can access this collection to get the count of available styles or reference specific styles by their index.

Syntax:
In xlwings, the Application object is typically accessed via the app object when you have an instance of Excel running. The SmartArtQuickStyles collection is a property of the Application object. The syntax to access it is:

app.api.SmartArtQuickStyles

This returns a SmartArtQuickStyles object, which is a collection. To interact with it, you can use methods and properties such as Count to get the number of styles, or Item(index) to retrieve a specific SmartArtQuickStyle object by its index (1-based). Note that xlwings uses the .api attribute to expose the underlying Excel object model, so this follows the standard Excel VBA object hierarchy but within Python.

Parameters:

  • index: An integer that specifies the position of the quick style in the collection. The index starts at 1. You can determine the total number of styles using the Count property.

Example:
Below is an xlwings code example that demonstrates how to access the SmartArtQuickStyles collection and print the count of available styles. It also shows how to reference a specific style and apply it to an existing SmartArt graphic in the active workbook. This assumes you have an Excel instance running with a workbook open that contains at least one SmartArt graphic.

import xlwings as xw

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

# Access the SmartArtQuickStyles collection
quick_styles = app.api.SmartArtQuickStyles

# Get the number of available quick styles
style_count = quick_styles.Count
print(f"Number of available SmartArt quick styles: {style_count}")

# Check if there are styles available
if style_count > 0:
    # Reference the first quick style in the collection (index 1)
    first_style = quick_styles.Item(1)
    print(f"First quick style name: {first_style.Name}")

# Assume we have a SmartArt graphic in the active sheet
# First, get the active sheet
active_sheet = app.api.ActiveSheet

# Try to access the first SmartArt graphic in the sheet
# Note: In practice, you need to ensure a SmartArt exists; this is simplified.
# Typically, you might loop through shapes to find SmartArt.
# Here, we assume the first shape is SmartArt for demonstration.
shapes = active_sheet.Shapes
if shapes.Count > 0:
# Check if the shape is a SmartArt graphic (Type 24 represents SmartArt in Excel)
target_shape = shapes.Item(1)
if target_shape.Type == 24: # 24 is msoSmartArt, a constant for SmartArt
    # Apply the first quick style to the SmartArt graphic
    target_shape.SmartArt.QuickStyle = first_style
    print("Applied the first quick style to the SmartArt graphic.")
else:
    print("The first shape is not a SmartArt graphic.")
else:
    print("No shapes found in the active sheet.")
else:
    print("No SmartArt quick styles are available.")

# Note: Error handling (e.g., for no SmartArt) should be added in production code.

How to use Application.SmartArtLayouts in the xlwings API way

The SmartArtLayouts member of the Application object in Excel’s object model provides access to the collection of SmartArt layouts available within the application. This collection is essential for programmatically managing and applying different visual layouts to SmartArt graphics, which are used to create professional diagrams and information graphics. Through xlwings, a powerful Python library for Excel automation, developers can interact with this collection to enumerate available layouts, retrieve specific layouts by their index or ID, and apply them to SmartArt shapes in workbooks. This functionality is particularly valuable in automating report generation, dashboard creation, and data visualization tasks where consistent and dynamic diagram styling is required.

In xlwings, the SmartArtLayouts member is accessed via the Application object. The syntax for referencing this collection is straightforward, as it does not require parameters for the property itself. However, when accessing individual layouts within the collection, methods and properties are used with specific arguments. The basic calling format is:

app.smart_art_layouts

Here, app represents an instance of the xlwings App class, which corresponds to the Excel Application object. The smart_art_layouts property returns a collection object that supports typical collection methods such as indexing. To retrieve a specific SmartArtLayout object, you can use an index (1-based) or a layout ID string. For example:

layout = app.smart_art_layouts[1] # Access by index
layout_by_id = app.smart_art_layouts('{LayoutID}') # Access by ID

The index refers to the position in the collection, which may vary based on the Excel version and installed templates. The layout ID is a unique string identifier for each layout, which can be obtained from Excel’s object model or by enumerating the collection. The SmartArtLayout object itself has properties like Id, Name, and Category, which provide details about the layout. For instance, layout.id returns the ID, and layout.name returns the display name. This allows for precise control when selecting layouts based on specific criteria.

A practical use case involves applying a SmartArt layout to an existing SmartArt graphic in a workbook. First, you need to identify the SmartArt shape, then set its layout using the Layout property. Below is an example code snippet that demonstrates this process:

import xlwings as xw

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

# Access the SmartArtLayouts collection and select a layout by index
smartart_layouts = app.smart_art_layouts
target_layout = smartart_layouts[3] # Assuming index 3 corresponds to a desired layout

# Open a workbook and select a worksheet
wb = app.books.open('example.xlsx')
ws = wb.sheets['Sheet1']

# Assume there is a SmartArt graphic in the worksheet; get the first shape (adjust as needed)
smartart_shape = ws.shapes[0] # This should be a SmartArt shape

# Apply the selected layout to the SmartArt graphic
smartart_shape.smart_art.layout = target_layout

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

In this example, we connect to Excel, retrieve the third layout from the SmartArtLayouts collection, and apply it to the first shape in a worksheet, assuming it is a SmartArt graphic. This automation can be extended to loop through multiple shapes or workbooks, applying consistent layouts based on dynamic conditions. Additionally, you can enumerate all available layouts to list their properties for reference:

for layout in app.smart_art_layouts:
    print(f"ID: {layout.id}, Name: {layout.name}, Category: {layout.category}")

How to use Application.SmartArtColors in the xlwings API way

The SmartArtColors member of the Application object in Excel provides programmatic access to the collection of color styles available for SmartArt graphics. This collection is essentially the set of color themes you see in the “Change Colors” gallery when working with a SmartArt graphic in the Excel interface. Through xlwings, you can retrieve this collection to apply predefined, coordinated color schemes to SmartArt objects, enhancing visual consistency and appeal without manually setting individual colors. This is particularly useful for automating report generation or ensuring corporate branding across multiple charts.

Syntax and Parameters

In xlwings, you access this property via the Application object. The property returns a SmartArtColors object, which is a collection of SmartArtColor objects. Each SmartArtColor object represents a specific color style (e.g., “Colorful – Accent Colors”, “Gradient Loop – Accent 1”).

The basic xlwings API call format is:

app.smart_art_colors
  • Return Value: An xlwings object representing the SmartArtColors collection. There are no parameters for this property call.

To work with individual color styles, you typically iterate through the collection or access items by their index (which corresponds to the order in the Excel gallery, usually starting at 1). A common subsequent step is to apply a color style to a specific SmartArt graphic by setting the SmartArt graphic’s ColorStyle property to the desired SmartArtColor object.

Code Example

The following xlwings code demonstrates how to list available SmartArt color styles and apply one to an existing SmartArt graphic on the active worksheet.

import xlwings as xw

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

# Access the SmartArtColors collection
color_collection = app.smart_art_colors

# Example 1: List the names of available color styles
print("Available SmartArt Color Styles:")
# The collection is 1-indexed. We use .count to get the number of items.
for i in range(1, color_collection.count + 1):
    color_style = color_collection(i) # Access by index
    print(f" {i}: {color_style.name}")

# Example 2: Apply a specific color style to a SmartArt graphic
# Assuming the first shape on the active sheet is a SmartArt graphic
wb = app.books.active
sheet = wb.sheets.active

# Target the first shape
target_shape = sheet.shapes[0]

# Check if the shape is a SmartArt graphic (requires platform-specific API caution)
# In practice, you might ensure this shape is SmartArt via its properties.
# Apply the third color style in the collection (e.g., "Gradient Range - Accent 1")
# First, get the desired SmartArtColor object
desired_color_style = color_collection(3)

# Apply it by setting the SmartArt graphic's ColorStyle property.
# Note: Direct property access might require using the .api property for full OM features.
target_shape.api.ColorStyle = desired_color_style

print(f"Applied '{desired_color_style.name}' to the SmartArt graphic.")

How to use Application.ShowToolTips in the xlwings API way

In the Excel object model, the Application.ShowToolTips property controls whether Excel displays ScreenTips for toolbar buttons. When enabled, hovering the mouse over a command button in the ribbon or toolbar will show a small descriptive text box. This can enhance user experience by providing quick guidance, especially in custom-built Excel applications or when distributing workbooks to less experienced users. From a developer’s perspective, managing this setting via xlwings allows you to ensure a consistent interface behavior programmatically, aligning with the application’s intended usability.

Syntax in xlwings:
The property is accessed through the xlwings.App object, which corresponds to the Excel Application. In xlwings, you typically interact with the active application instance or create a new one. The property is a Boolean value.

import xlwings as xw

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

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

# Set the ShowToolTips property
app.api.ShowToolTips = True # or False

Here, app.api provides direct access to the underlying Excel Application object’s COM interface, allowing you to use the standard Excel VBA properties and methods. The ShowToolTips property accepts a Boolean: True turns on ScreenTips, False turns them off. Note that changes affect the entire Excel application, not just a specific workbook.

Code Examples:

  1. Checking the Current Setting:
    This is useful for diagnostics or to conditionally adjust other settings based on the current state.
import xlwings as xw
app = xw.apps.active
if app.api.ShowToolTips:
    print("ToolTips are currently enabled.")
else:
    print("ToolTips are disabled.")
  1. Temporarily Disabling ToolTips:
    You might want to turn off ToolTips during a macro-intensive process to prevent visual distractions, then restore the original setting.
import xlwings as xw
app = xw.apps.active
original_setting = app.api.ShowToolTips
try:
    app.api.ShowToolTips = False
    # Perform tasks where ToolTips are not needed
    # e.g., automated data processing
    print("ToolTips disabled for operations.")
finally:
    app.api.ShowToolTips = original_setting
    print(f"ToolTips restored to {original_setting}.")
  1. Ensuring ToolTips are Enabled for User Interaction:
    In a user-facing application, you might enforce ToolTips to be on to aid navigation.
import xlwings as xw
# Start or connect to Excel
app = xw.App(visible=True) # New instance, visible
app.api.ShowToolTips = True
# Open a workbook and perform tasks
wb = app.books.open('example.xlsx')
# ... additional code
# The user will see ToolTips throughout the session

How to use Application.ShowStartupDialog in the xlwings API way

The Application.ShowStartupDialog property in Excel’s object model controls whether the Excel startup screen (also known as the “Start” screen or backstage view) is displayed when Excel is launched. This screen typically appears when you open Excel without specifying a workbook, offering options to create a new workbook, open recent files, or browse for other files. In xlwings, you can access and manipulate this property through the App object, which represents the Excel application instance. This allows you to programmatically enable or disable the startup dialog based on your automation needs, such as suppressing it for seamless background operations or ensuring it appears for user interaction in custom applications.

Syntax in xlwings:
The property is accessed via the App object in xlwings. The syntax is straightforward:

app = xw.App() # Get the current or create a new Excel application instance
value = app.api.ShowStartupDialog # Get the current value
app.api.ShowStartupDialog = new_value # Set a new value
  • app: An instance of the xlwings App class, representing the Excel application.
  • app.api: Provides access to the underlying Excel object model (via pywin32 on Windows or appscript on macOS).
  • ShowStartupDialog: A property that accepts Boolean values:
  • True (or 1): Enables the startup dialog, so it will display when Excel starts.
  • False (or 0): Disables the startup dialog, so Excel opens directly without showing the screen.

Example Usage:
Here are practical examples demonstrating how to use ShowStartupDialog with xlwings:

  1. Check the Current Setting:
    This code retrieves the current state of the startup dialog and prints it.
import xlwings as xw
app = xw.App(visible=True) # Ensure Excel is visible
current_setting = app.api.ShowStartupDialog
print(f"Startup dialog is currently enabled: {current_setting}")
app.quit() # Close the application
  1. Disable the Startup Dialog:
    This example sets the property to False to hide the startup screen. It’s useful for automation scripts where you want Excel to open silently.
import xlwings as xw
app = xw.App(visible=True)
app.api.ShowStartupDialog = False
print("Startup dialog has been disabled.")
# Now, if you restart Excel manually, the startup screen won't appear.
# Note: This change may persist in Excel's settings, affecting future sessions.
app.quit()
  1. Enable the Startup Dialog and Open a New Workbook:
    This code ensures the startup dialog is enabled, then opens a new workbook. This can be part of a setup routine for user-facing applications.
import xlwings as xw
app = xw.App(visible=True)
app.api.ShowStartupDialog = True
workbook = app.books.add() # Add a new workbook
print("Startup dialog enabled and a new workbook created.")
# The startup screen will show next time Excel is launched without a workbook.
workbook.save("NewWorkbook.xlsx")
app.quit()