Blog
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
SmartArtColorscollection. 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:
- 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.")
- 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}.")
- 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 xlwingsAppclass, 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(or1): Enables the startup dialog, so it will display when Excel starts.False(or0): 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:
- 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
- Disable the Startup Dialog:
This example sets the property toFalseto 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()
- 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()
How to use Application.ShowSelectionFloaties in the xlwings API way
The ShowSelectionFloaties property of the Application object in Excel is a useful feature for controlling the visibility of selection floaties—those small, dynamic pop-up toolbars that appear near a selected cell or range in Excel, offering quick access to formatting and data analysis tools like sorting, filtering, and chart recommendations. In xlwings, this property can be accessed and manipulated to enhance user experience by hiding these floaties when they might be distracting, such as during automated report generation or when running macros that require a clean interface.
Syntax and Usage in xlwings
In xlwings, you interact with Excel’s VBA object model through the app object, which represents the Excel application. The ShowSelectionFloaties property is a boolean property, meaning it can be set to either True or False. The syntax for accessing and setting this property is straightforward:
app.api.ShowSelectionFloaties
- Property Type: Boolean (
boolin Python). - Get Value: To check the current state, simply read the property:
current_state = app.api.ShowSelectionFloaties. This returnsTrueif selection floaties are visible, andFalseif they are hidden. - Set Value: To change the visibility, assign a boolean value:
app.api.ShowSelectionFloaties = Falseto hide floaties, orapp.api.ShowSelectionFloaties = Trueto show them.
There are no parameters for this property, as it is a simple toggle. However, it’s important to note that changes made via xlwings are applied immediately to the Excel instance and affect all open workbooks. This property is part of the Excel Application object, so it controls the global setting for the entire Excel session.
Code Examples
Here are practical examples of using ShowSelectionFloaties in xlwings to manage the visibility of selection floaties:
- Hiding Selection Floaties During an Automated Task
This example demonstrates how to hide floaties before performing a series of operations to prevent them from interfering with the automation, then restore the original setting afterward.
import xlwings as xw
# Connect to the active Excel instance or start a new one
app = xw.apps.active
# Save the current state of ShowSelectionFloaties
original_state = app.api.ShowSelectionFloaties
# Hide the selection floaties
app.api.ShowSelectionFloaties = False
# Perform automated tasks, such as formatting a range
wb = app.books.active
sheet = wb.sheets[0]
sheet.range('A1:D10').value = [[i * j for j in range(1, 5)] for i in range(1, 11)]
sheet.range('A1:D10').api.AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2)
# Restore the original state of ShowSelectionFloaties
app.api.ShowSelectionFloaties = original_state
- Toggling Selection Floaties Based on User Input
In this scenario, the script checks the current visibility and toggles it based on a condition, such as user preference from a simple input.
import xlwings as xw
app = xw.apps.active
# Simulate a user preference (e.g., from a configuration file or input)
user_wants_floaties = False # Assume user prefers hidden floaties
if user_wants_floaties:
app.api.ShowSelectionFloaties = True
print("Selection floaties are now visible.")
else:
app.api.ShowSelectionFloaties = False
print("Selection floaties are now hidden.")
- Ensuring a Clean Interface for a Dashboard
When generating a dashboard, you might want to hide floaties to maintain a professional appearance, especially before saving or exporting the workbook.
import xlwings as xw
app = xw.apps.active
wb = app.books.active
# Hide floaties before finalizing the dashboard
app.api.ShowSelectionFloaties = False
# Perform dashboard updates (e.g., refresh charts, pivot tables)
# ... (your dashboard code here)
# Save the workbook with floaties hidden
wb.save(r'C:\Path\To\Dashboard.xlsx')
# Optionally, re-enable floaties if needed for further interaction
# app.api.ShowSelectionFloaties = True
How to use Application.ShowQuickAnalysis in the xlwings API way
The ShowQuickAnalysis property of the Application object in Excel, accessible via the xlwings library in Python, provides a convenient way to programmatically trigger the Quick Analysis feature. This feature, when invoked, offers users a context-sensitive menu with various tools for data analysis and visualization, such as conditional formatting, charts, totals, tables, and sparklines. It is particularly useful for enhancing data presentation and gaining insights directly from a selected range without navigating through multiple ribbon tabs. In xlwings, this functionality is exposed as a property of the application instance, allowing for seamless integration into automated Excel workflows.
The syntax for accessing this property in xlwings is straightforward. It is called on the application object, which represents the Excel instance. Since ShowQuickAnalysis is a property, it can be set to True or False to control the visibility of the Quick Analysis tooltip. Typically, it is set to True to display the tooltip for a specific range. The property does not take any arguments directly, but its effect is applied to the currently selected range in the active workbook. To use it effectively, you should first select the desired range of cells before setting the property.
Here is a basic code example demonstrating its usage:
import xlwings as xw
# Connect to the active Excel instance or start a new one
app = xw.apps.active
# Open a workbook or use the active one
wb = app.books.active
# Select a specific range, e.g., A1:D10, which contains data for analysis
ws = wb.sheets.active
ws.range('A1:D10').select()
# Show the Quick Analysis tooltip for the selected range
app.ShowQuickAnalysis = True
How to use Application.ShowMenuFloaties in the xlwings API way
The ShowMenuFloaties member of the Application object in Excel controls whether context-sensitive tooltips (also known as “ScreenTips” or “floaties”) are displayed for menus and commands in the Excel user interface. This property is part of the Excel object model and can be accessed via the xlwings library in Python to programmatically manage the visibility of these UI hints, which can enhance user experience or reduce on-screen clutter during automated processes.
Functionality:ShowMenuFloaties is a Boolean property that determines if Excel shows descriptive tooltips when the user hovers over menu items, ribbon buttons, or other command elements. When set to True, these floaties are visible; when False, they are hidden. This can be useful in automation scripts where you want to standardize the UI state or minimize distractions during macro execution.
Syntax in xlwings:
In xlwings, you access this property through the app object, which represents the Excel Application. The syntax is straightforward as it involves getting or setting a property value. There are no parameters for this property, as it is a simple Boolean toggle.
- To get the current state:
current_state = app.api.ShowMenuFloaties
This returns True if menu floaties are shown, False otherwise.
- To set the state:
app.api.ShowMenuFloaties = False # Hides menu floaties
or
app.api.ShowMenuFloaties = True # Shows menu floaties
Code Examples:
Here are practical xlwings API examples demonstrating how to use ShowMenuFloaties:
- Hiding Menu Floaties During an Automation Task:
This example temporarily disables menu floaties to clean up the UI while performing data operations, then restores the original setting.
import xlwings as xw
# Connect to the active Excel instance
app = xw.apps.active
# Store the original state
original_state = app.api.ShowMenuFloaties
# Hide menu floaties
app.api.ShowMenuFloaties = False
# Perform some Excel tasks (e.g., data processing)
wb = app.books.active
sheet = wb.sheets[0]
sheet.range('A1').value = 'Processing data...'
# ... additional automation code ...
# Restore the original state
app.api.ShowMenuFloaties = original_state
- Checking and Toggling the Menu Floaties Setting:
This example checks the current visibility and toggles it based on a condition.
import xlwings as xw
app = xw.apps.active
# Check if menu floaties are currently shown
if app.api.ShowMenuFloaties:
print("Menu floaties are visible. Hiding them now.")
app.api.ShowMenuFloaties = False
else:
print("Menu floaties are hidden. Showing them now.")
app.api.ShowMenuFloaties = True
- Ensuring a Clean UI for a Report Generation Macro:
In this scenario, menu floaties are turned off during report generation to prevent visual interference, and the setting is reverted afterward.
import xlwings as xw
def generate_report():
app = xw.apps.active
# Disable menu floaties
app.api.ShowMenuFloaties = False
# Generate report logic
wb = app.books.active
# ... code to format and populate the report ...
# Re-enable menu floaties
app.api.ShowMenuFloaties = True
print("Report generated with menu floaties managed.")
# Run the function
generate_report()
How to use Application.ShowDevTools in the xlwings API way
The ShowDevTools member of the Application object in Excel’s object model provides control over the visibility of the VBA (Visual Basic for Applications) development environment, commonly known as the VBA Editor or IDE (Integrated Development Environment). When automating Excel with xlwings, this property allows you to programmatically show or hide the VBA Editor window, which is useful during development, debugging, or when creating macros and user forms. It’s a Boolean property that can be set to True to display the editor or False to hide it, and it can also be read to check the current visibility state.
In xlwings, you access this property through the api property of the App or Book objects, which exposes the underlying Excel VBA object model. The syntax for using ShowDevTools is straightforward, as it maps directly to the Excel object model.
Syntax in xlwings:
- To get the current visibility state:
app.api.ShowDevTools - To set the visibility state:
app.api.ShowDevTools = Trueorapp.api.ShowDevTools = False
Where app is an instance of xw.App representing the Excel application. The property accepts and returns a Boolean value:
- True: Makes the VBA Editor visible.
- False: Hides the VBA Editor.
Note: This property is specific to the Excel application instance and affects the VBA Editor globally for that instance. It may not be available or have an effect if VBA is disabled or not installed (e.g., in some Excel runtime environments). Always ensure the Excel instance has VBA support.
Code Examples with xlwings:
- Showing the VBA Editor:
This example starts an Excel application, makes it visible, and then opens the VBA Editor.
import xlwings as xw
# Start a new Excel application
app = xw.App(visible=True)
# Show the VBA Developer Tools (Editor)
app.api.ShowDevTools = True
# Keep the application open for demonstration
input("Press Enter to close Excel...")
app.quit()
- Toggling VBA Editor Visibility:
This example checks the current state of the VBA Editor, toggles it, and prints a message.
import xlwings as xw
app = xw.App(visible=True)
# Get current visibility state
current_state = app.api.ShowDevTools
print(f"VBA Editor is currently visible: {current_state}")
# Toggle the state
app.api.ShowDevTools = not current_state
print(f"Toggled visibility. Now visible: {app.api.ShowDevTools}")
# Clean up
app.quit()
- Conditional Display Based on Debug Mode:
In a script, you might want to show the VBA Editor only during debugging or development phases.
import xlwings as xw
DEBUG_MODE = True # Set to False in production
app = xw.App(visible=True)
if DEBUG_MODE:
app.api.ShowDevTools = True
print("Debug mode: VBA Editor shown.")
else:
app.api.ShowDevTools = False
print("Production mode: VBA Editor hidden.")
# Perform other automation tasks...
app.quit()
How to use Application.ShowChartTipValues in the xlwings API way
In the Excel object model, the Application.ShowChartTipValues property is a member of the top-level Application object. This property controls whether chart tip values (also known as data labels or tooltips) are displayed when you hover the mouse pointer over a data point in a chart within Excel. When enabled, users can see the exact numeric value of a data point directly on the chart, enhancing data visualization and analysis. This setting applies globally to all open workbooks in the Excel instance.
In xlwings, you can access and manipulate this property through the api property of the App object, which provides a direct gateway to the underlying Excel Application object via the COM interface. The xlwings API call follows the pattern: app.api.ShowChartTipValues, where app is an instance of xlwings.App. This property is a Boolean value, meaning it can be set to True to enable chart tip values or False to disable them. You can also retrieve its current state to check if the feature is active.
The syntax for using ShowChartTipValues in xlwings is straightforward:
- To get the current setting:
current_setting = app.api.ShowChartTipValues - To set the setting:
app.api.ShowChartTipValues = Trueorapp.api.ShowChartTipValues = False
There are no parameters for this property, as it is a simple Boolean attribute. However, it’s important to note that changes made to this property affect the entire Excel application session. This means that all charts across all open workbooks will adhere to this setting until it is changed again or Excel is closed. It’s a useful feature for presentations or reports where you might want to temporarily hide or show data values for clarity.
Here is a practical xlwings API code example that demonstrates how to use the ShowChartTipValues property:
import xlwings as xw
# Connect to the active Excel instance or start a new one
app = xw.apps.active if xw.apps.active else xw.App()
# Get the current state of ShowChartTipValues
current_state = app.api.ShowChartTipValues
print(f"Current ShowChartTipValues setting: {current_state}")
# Disable chart tip values
app.api.ShowChartTipValues = False
print("Chart tip values have been disabled.")
# Perform some chart-related operations, e.g., open a workbook with a chart
wb = app.books.open('example.xlsx')
chart = wb.sheets[0].charts[0] # Assuming the first chart on the first sheet
# At this point, hovering over chart data points will not show values
# Re-enable chart tip values
app.api.ShowChartTipValues = True
print("Chart tip values have been re-enabled.")
# Close the workbook without saving
wb.close()
# Optionally, reset to the original state if needed
app.api.ShowChartTipValues = current_state
# Quit the Excel application if it was started by this script
if not xw.apps.active:
app.quit()
How to use Application.ShowChartTipNames in the xlwings API way
The ShowChartTipNames property of the Application object in Excel is a setting that controls whether chart tip names are displayed. Chart tips are the small pop-up labels that appear when you hover the mouse pointer over a chart element, such as a data point, series, or axis title. These tips typically show the name and value of the element. When ShowChartTipNames is set to True, these names are included in the tooltip. When set to False, only the values are shown, if applicable. This property is part of a group of settings that manage on-screen feedback and can be useful for creating cleaner visual presentations or for users who are already familiar with the chart’s data structure and do not require the additional descriptive text.
In the xlwings library, which provides a Pythonic interface to automate and interact with Excel, you access this property through the Application object. The syntax is straightforward, as it is a simple property getter and setter. The property expects a Boolean value (True or False).
xlwings API Syntax:
app = xw.App() # Get the active or a new Excel application instance
# To get the current setting
current_setting = app.api.ShowChartTipNames
# To set the property
app.api.ShowChartTipNames = True # or False
Here, app.api provides direct access to the underlying Excel VBA object model. The ShowChartTipNames property does not take any arguments; it is simply read or written to.
Code Example:
The following example demonstrates how to toggle the ShowChartTipNames setting and verify its state. This can be integrated into a larger script that prepares an Excel environment for a specific reporting task, ensuring that chart tooltips conform to a desired standard.
import xlwings as xw
# Connect to the active Excel instance
with xw.App(visible=True) as app:
# Get the current setting and print it
original_setting = app.api.ShowChartTipNames
print(f"Original ShowChartTipNames setting: {original_setting}")
# Disable the display of names in chart tips
app.api.ShowChartTipNames = False
print("ShowChartTipNames has been set to False. Chart tooltips will now only show values.")
# For demonstration, create a simple chart to see the effect
wb = app.books.add()
sheet = wb.sheets[0]
# Add some sample data
sheet.range('A1').value = [['Category', 'Value'],
['A', 10],
['B', 20],
['C', 15]]
# Create a chart
chart = sheet.charts.add()
chart.set_source_data(sheet.range('A1').expand())
chart.chart_type = 'column_clustered'
chart.api[1].HasTitle = True
chart.api[1].ChartTitle.Text = "Sample Chart"
# Pause to allow user to hover over chart and observe tooltips
input("Hover over a column in the chart. The tooltip should show only the value (e.g., '20'). Press Enter to continue...")
# Re-enable the display of names
app.api.ShowChartTipNames = True
print("ShowChartTipNames has been restored to True. Tooltips will now show names and values.")
input("Hover over a column again. The tooltip should now show both name and value (e.g., 'B: 20'). Press Enter to exit...")
# Optionally, restore the original setting before closing
app.api.ShowChartTipNames = original_setting
wb.close()
How to use Application.SheetsInNewWorkbook in the xlwings API way
The SheetsInNewWorkbook property of the Application object in Excel specifies the number of worksheets that are automatically included when a new workbook is created. This setting is a global option within the Excel application instance, allowing users or automation scripts to define a default sheet count, which can improve efficiency by avoiding the need to manually add sheets after workbook creation. In xlwings, this property is accessed through the Application object, providing a programmatic way to both retrieve and modify this default value.
Functionality:
The primary function is to control the default number of worksheets in new workbooks. This is particularly useful in automation scenarios where a consistent starting structure is required, or when preparing templates that need multiple sheets by default.
Syntax:
# To get the current setting
current_sheet_count = xw.apps[0].api.SheetsInNewWorkbook
# To set a new value
xw.apps[0].api.SheetsInNewWorkbook = new_count
xw.apps[0]: Represents the first (or a specific) Excel application instance controlled by xlwings. Usexw.apps.activefor the active instance if multiple are open..api: Provides direct access to the underlying Excel object model (the COM API).SheetsInNewWorkbook: The property being accessed. It expects an integer value.
Parameter/Value Details:
- Type: Read/Write Property (Integer).
- Value Range: The number must be an integer between 1 and 255, inclusive. Excel enforces these limits.
- Default: Typically 1 in a standard Excel installation.
- Persistence: This is an application-level setting in the current session. It is not permanently saved between Excel sessions unless configured within Excel’s options or set via a macro that runs on startup.
Code Examples:
- Retrieving the Current Default:
import xlwings as xw
# Connect to the active Excel instance
app = xw.apps.active
# Get the current default number of sheets
default_sheets = app.api.SheetsInNewWorkbook
print(f"New workbooks currently start with {default_sheets} sheet(s).")
# Output example: New workbooks currently start with 1 sheet(s).
- Changing the Default and Creating a Workbook:
import xlwings as xw
app = xw.apps.active
# Set the default to 3 worksheets
app.api.SheetsInNewWorkbook = 3
# Create a new workbook. It will now contain 3 worksheets automatically.
new_wb = app.books.add()
print(f"New workbook has {len(new_wb.sheets)} sheets.")
# Output: New workbook has 3 sheets.
# List the sheet names
for sheet in new_wb.sheets:
print(sheet.name)
# Output: Sheet1, Sheet2, Sheet3
- Resetting to the Standard Default:
import xlwings as xw
app = xw.apps.active
# Reset to the common default of 1 sheet
app.api.SheetsInNewWorkbook = 1