Archive

How to use Application.CursorMovement in the xlwings API way

In the xlwings library, the Application object’s CursorMovement property provides control over the movement of the cell cursor after pressing the Enter key in Microsoft Excel. This property is particularly useful for customizing user interaction within a workbook, enhancing data entry efficiency by dictating the direction in which the selection moves post-data entry.

Functionality:
The CursorMovement property determines the direction in which the active cell moves when the Enter key is pressed. This can be set to move down, up, left, or right, depending on the user’s preference or the specific workflow requirements. By default, Excel moves the cursor down, but this can be adjusted programmatically via xlwings to streamline repetitive data entry tasks, such as filling rows horizontally or navigating vertically in a structured manner.

Syntax:
In xlwings, the CursorMovement property is accessed through the Application object. The property can be both read and set. The syntax is as follows:

app = xw.App()
app.api.CursorMovement

Here, app.api provides access to the underlying Excel object model. The CursorMovement property accepts integer values that correspond to specific movement directions, as defined in the Excel enumeration xlDirection. The primary values are:

  • xlDown (value: -4121): Moves the cursor down.
  • xlUp (value: -4162): Moves the cursor up.
  • xlToLeft (value: -4159): Moves the cursor to the left.
  • xlToRight (value: -4161): Moves the cursor to the right.

To set the property, assign one of these integer values. For example, to move the cursor to the right, use:

app.api.CursorMovement = -4161 # xlToRight

Example Usage:
Below are practical xlwings code examples demonstrating how to use the CursorMovement property:

  1. Setting Cursor Movement to Move Right:
    This example opens an Excel workbook and configures the cursor to move right after pressing Enter, which is useful for entering data across rows.
import xlwings as xw
app = xw.App(visible=True)
workbook = app.books.open('example.xlsx')
app.api.CursorMovement = -4161 # Set to move right
print(f"Cursor movement set to: {app.api.CursorMovement}")
# Perform data entry or other operations
app.quit()
  1. Reading and Changing Cursor Movement Dynamically:
    This example reads the current cursor movement setting, changes it based on a condition, and then restores the original setting.
import xlwings as xw
app = xw.App(visible=False)
original_movement = app.api.CursorMovement
print(f"Original cursor movement: {original_movement}")

if original_movement == -4121: # If currently moving down
    app.api.CursorMovement = -4162 # Change to move up
    print("Cursor movement changed to move up.")
else:
    app.api.CursorMovement = -4121 # Default to move down
    print("Cursor movement changed to move down.")

# Restore original setting after operations
app.api.CursorMovement = original_movement
app.quit()
  1. Using Cursor Movement in a Data Entry Loop:
    This example simulates a data entry scenario where the cursor movement is set to move down, and then a loop enters sample data into a column.
import xlwings as xw
app = xw.App(visible=True)
workbook = app.books.add()
sheet = workbook.sheets[0]
app.api.CursorMovement = -4121 # Move down

# Enter data into cells A1 through A5
for i in range(1, 6):
    sheet.range(f'A{i}').value = f'Data {i}'
    # In a real scenario, pressing Enter would move the cursor down automatically

print("Data entry complete with cursor moving down.")
app.quit()

How to use Application.Cursor in the xlwings API way

In the Excel object model, the Application.Cursor property is a member of the top-level Application object, which represents the entire Excel application. This property controls the visual appearance of the mouse cursor (pointer) in Excel. It is particularly useful in automation scenarios where you want to provide visual feedback to users, such as indicating that a long-running operation is in progress. By changing the cursor, you can enhance the user experience by signaling that the application is busy or that a specific action is required.

Functionality:
The Application.Cursor property allows you to get or set the mouse cursor shape displayed in Excel. It can be used to change the cursor to standard shapes like an arrow, an I-beam for text selection, or a wait cursor (e.g., an hourglass or spinning wheel) during lengthy operations. This helps in making automated processes more user-friendly by visually communicating the application’s state.

Syntax:
In xlwings, you can access the Application.Cursor property through the app object, which represents the Excel application. The property is used to get or set the cursor type. The syntax is as follows:

  • To get the current cursor: current_cursor = app.api.Cursor
  • To set the cursor to a new value: app.api.Cursor = cursor_value

Here, app is an instance of the xlwings App class, typically created with xw.App() or accessed via xw.apps. The api attribute provides direct access to the underlying Excel object model. The cursor_value is an integer or enumeration constant that specifies the cursor shape. In Excel VBA, these values are defined by the XlMousePointer enumeration. Common values include:

  • xlDefault (or 0): The default cursor (usually an arrow).
  • xlWait (or 1): A wait cursor (e.g., hourglass), indicating that Excel is busy.
  • xlIBeam (or 3): An I-beam cursor, used for text selection.
  • xlNorthwestArrow (or 2): A northwest arrow cursor.

To use these in xlwings, you can define constants or use the integer values directly. For example, xlWait corresponds to the integer 1.

Example:
Below is an xlwings code example that demonstrates how to use the Application.Cursor property to change the mouse cursor during a time-consuming operation, such as processing data in a worksheet. This example shows setting the cursor to a wait state, performing a task, and then resetting it to the default.

import xlwings as xw
import time

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

# Set the cursor to wait (hourglass) to indicate busy state
app.api.Cursor = 1 # Using integer value for xlWait
print("Cursor set to wait state. Processing data...")

# Simulate a long-running task, e.g., iterating through cells
try:
    # Access the active workbook and worksheet
    wb = app.books.active
    ws = wb.sheets.active

    # Example operation: sum values in a range (this could be any intensive task)
total = 0
    for cell in ws.range("A1:A10"): # Process a range of cells
        if cell.value is not None:
            total += cell.value
            time.sleep(0.1) # Simulate delay for demonstration

            print(f"Total sum from A1:A10 is: {total}")

finally:
    # Always reset the cursor to default after the operation
    app.api.Cursor = 0 # Using integer value for xlDefault
    print("Cursor reset to default state.")

# Optional: Close the app if it was started in this script
# app.quit()

How to use Application.Creator in the xlwings API way

The Creator property of the Application object in Excel’s object model is a read-only attribute that returns a 32-bit integer representing the application that created the file. In Excel, this value is typically used to identify whether the file was created by Microsoft Excel or another application, such as a third-party tool or a different version of Excel. In xlwings, the Creator property can be accessed to retrieve this identifier, which can be useful for compatibility checks, file validation, or logging purposes when automating Excel tasks.

Functionality:
The Creator property helps determine the origin application of an Excel file. For instance, if a file was created by Excel, the Creator value will correspond to Microsoft Excel’s identifier. This can be essential in scenarios where you need to ensure that files are processed only from specific sources or to troubleshoot issues related to file creation.

Syntax in xlwings:
In xlwings, you can access the Creator property through the app object, which represents the Excel application. The syntax is straightforward, as it is a property without parameters. Here’s the general format:

creator_value = app.api.Creator
  • app: This is the xlwings App instance connected to Excel.
  • api: This attribute provides access to the underlying Excel object model, allowing direct interaction with properties like Creator.
  • Creator: The property that returns an integer representing the creator application.

The returned value is an integer. For Microsoft Excel, the typical value is 1480803660 (which corresponds to the hexadecimal 0x5843454C, representing “XCEL” in ASCII). Other applications may have different values. You can compare this integer to known constants to identify the creator.

Example Usage:
Below is a code example that demonstrates how to use the Creator property in xlwings to check if the current Excel file was created by Microsoft Excel. This example assumes you have an Excel application open and connected via xlwings.

import xlwings as xw

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

# Access the Creator property
creator_code = app.api.Creator

# Define known creator codes (example for Microsoft Excel)
EXCEL_CREATOR = 1480803660 # This is the standard value for Excel

# Check the creator and print the result
if creator_code == EXCEL_CREATOR:
    print("The file was created by Microsoft Excel.")
else:
    print(f"The file was created by another application. Creator code: {creator_code}")

# You can also convert the code to a hexadecimal string for easier interpretation
hex_creator = hex(creator_code)
print(f"Creator code in hexadecimal: {hex_creator}")

How to use Application.CopyObjectsWithCells in the xlwings API way

Application.CopyObjectsWithCells Property in xlwings

The Application.CopyObjectsWithCells property in Excel, accessible via the xlwings API, controls whether drawing objects (such as shapes, charts, pictures, and other embedded objects) are copied or moved along with their associated cells during cut, copy, or fill operations in a worksheet. This property is a global application-level setting, meaning it affects the behavior across all open workbooks in the Excel instance controlled by xlwings. It is particularly useful for automating tasks where you need to ensure that graphical elements remain attached to specific data ranges when those ranges are manipulated.

Syntax and Parameters in xlwings

In xlwings, you interact with this property through the app object, which represents the Excel Application. The property is exposed as a read/write Boolean attribute.

  • Property Access:
  • app.api.CopyObjectsWithCells (using the .api attribute to access the underlying Excel object model directly).
  • Alternatively, you can use app.engine.api.CopyObjectsWithCells if working with a specific engine context in more advanced scenarios, but typically the app.api route is standard.
  • Value:
  • True: (Default) Drawing objects are copied, moved, or filled along with cells.
  • False: Drawing objects remain in their original positions on the worksheet; only the cell contents and formats are affected by the operation.

Code Examples

Here are practical xlwings code snippets demonstrating how to get and set this property, and its impact on operations.

  1. Checking the Current Setting:
import xlwings as xw

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

# Get the current value of CopyObjectsWithCells
current_setting = app.api.CopyObjectsWithCells
print(f"CopyObjectsWithCells is currently set to: {current_setting}")
# Output will be True or False
  1. Changing the Setting and Performing a Copy Operation:
    This example disables the copying of objects, copies a cell range, and then restores the original setting.
import xlwings as xw

app = xw.apps.active
wb = app.books.active
sheet = wb.sheets[0]

# Assume cell A1 has a shape (e.g., a rectangle) over it and contains the number 10.
original_setting = app.api.CopyObjectsWithCells

# Set to False: Objects will NOT move with cells.
app.api.CopyObjectsWithCells = False
print("Set CopyObjectsWithCells to False.")

# Copy cell A1 to B1. Only the value (10) will be copied.
sheet.range('A1').copy(sheet.range('B1'))

# Verify: B1 now contains 10, but the shape remains only over A1.

# Restore the original application setting
app.api.CopyObjectsWithCells = original_setting
print("Restored original setting.")
  1. Automating a Task with Controlled Object Behavior:
    A more integrated example where you temporarily enable object copying to duplicate a data section with its associated chart.
import xlwings as xw

app = xw.apps.active
wb = app.books['Report.xlsx']
data_sheet = wb.sheets['MonthlyData']

# Ensure objects are copied with cells for this specific operation
app.api.CopyObjectsWithCells = True

# Define the source range (A1:D10) which includes data and an embedded chart object
source_range = data_sheet.range('A1:D10')
# Define the target starting cell
target_range = data_sheet.range('A12')

# Copy the entire block, including the chart
source_range.copy(target_range)

# Optional: Reset to default (True) or a previous state if needed for other macros/users.
# app.api.CopyObjectsWithCells = False

How to use Application.ControlCharacters in the xlwings API way

The Application.ControlCharacters property in Excel’s object model is a member of the Application object that controls the display of certain control characters within cells. Specifically, it determines whether control characters (such as line breaks, carriage returns, or tab characters) are shown as visible symbols or are rendered as their functional effects (like actual line breaks). This property is particularly useful when dealing with text data imported from other systems that may contain these characters, allowing users to toggle their visibility for editing or debugging purposes. In xlwings, this property can be accessed and modified to customize how Excel handles these characters in the user interface.

In terms of syntax, the ControlCharacters property is accessed through the Application object in xlwings. The xlwings API provides a straightforward way to interact with this property using Python. The property is a Boolean value, where True means that control characters are displayed as visible symbols (e.g., a small square for a line break), and False means they are rendered normally (e.g., causing an actual line break in the cell). The xlwings call format follows the pattern of accessing properties from the app object, which represents the Excel application. For example, to get the current setting, you use app.api.ControlCharacters, and to set it, you assign a value like app.api.ControlCharacters = True. Note that app must be an instance of the xlwings App class connected to a running Excel application. This property does not take additional parameters; it is a simple read/write property that affects the entire Excel instance.

Here is a code example demonstrating the usage of Application.ControlCharacters with xlwings. First, ensure you have xlwings installed and an Excel workbook open. The example will toggle the display of control characters and print the current state:

import xlwings as xw

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

# Get the current ControlCharacters setting
current_setting = app.api.ControlCharacters
print(f"Current ControlCharacters setting: {current_setting}")

# Set ControlCharacters to True to show symbols
app.api.ControlCharacters = True
print("ControlCharacters set to True. Control characters will display as symbols.")

# Set ControlCharacters to False to render normally
app.api.ControlCharacters = False
print("ControlCharacters set to False. Control characters will render functionally.")

# Verify the change by getting the setting again
updated_setting = app.api.ControlCharacters
print(f"Updated ControlCharacters setting: {updated_setting}")

How to use Application.ConstrainNumeric in the xlwings API way

The ConstrainNumeric member of the Excel Application object is a property that controls whether Excel restricts numeric entry to a specific set of characters. This setting is particularly useful in environments where data entry must be standardized, such as when using numeric keypads or in locales with specific decimal and thousands separators. When enabled, it limits the characters that can be typed into cells to digits (0-9), the decimal point (which may vary by locale), the minus sign (-), and the slash (/) for fractions. This helps prevent accidental input of non-numeric characters, ensuring data integrity in worksheets that require pure numeric values. In xlwings, this property can be accessed and modified to automate the configuration of Excel’s behavior during data entry tasks, making it valuable for scripting scenarios where consistent numeric input is critical.

In terms of syntax, the ConstrainNumeric property is a Boolean type. It can be set to True to enforce numeric constraints or False to disable them. The xlwings API provides a straightforward way to interact with this property through the Application object. The general syntax is:

app.constrain_numeric

Here, app refers to an instance of the xlwings App class, which represents the Excel application. The property is read/write, meaning you can both retrieve its current value and assign a new one. For example, to enable numeric constraints, you would set app.constrain_numeric = True. Conversely, to check the current setting, you can read it with current_setting = app.constrain_numeric. Note that in xlwings, property names are typically in snake_case to align with Python conventions, even though the original VBA property is in PascalCase (e.g., ConstrainNumeric in VBA becomes constrain_numeric in xlwings).

To illustrate the usage, consider the following xlwings code examples. First, you might want to ensure numeric constraints are active before performing data entry operations. This can be done by setting the property at the start of a script:

import xlwings as xw

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

# Enable ConstrainNumeric to restrict input to numeric characters
app.constrain_numeric = True

print("Numeric constraints are now enabled.")

In a more dynamic scenario, you might toggle the setting based on user input or specific conditions. For instance, if you are automating a workbook that requires temporary relaxation of numeric constraints for text entry, you could disable and re-enable it as needed:

import xlwings as xw

app = xw.apps.active

# Disable numeric constraints to allow non-numeric input
app.constrain_numeric = False
print("Numeric constraints disabled. You can now enter text or symbols.")

# Perform some operations that require non-numeric input
# ...

# Re-enable numeric constraints after the operations
app.constrain_numeric = True
print("Numeric constraints re-enabled.")

Additionally, you can retrieve the current setting to log or make decisions in your script. This is useful for ensuring that the Excel environment is configured as expected before proceeding with data processing:

import xlwings as xw

app = xw.apps.active

# Check the current state of ConstrainNumeric
if app.constrain_numeric:
    print("Numeric entry is currently constrained to digits, decimal, minus, and slash.")
else:
    print("Numeric entry is not constrained; any characters can be input.")

How to use Application.CommandUnderlines in the xlwings API way

The Application.CommandUnderlines property in Excel VBA controls the underline style used for menu command access keys (the underlined letter that, when pressed with the Alt key, activates a command). In the xlwings Python library, which provides a programmatic interface to Excel’s object model, you can access and manipulate this property to adjust the user interface behavior of the Excel application instance. This can be useful for ensuring consistency in application appearance or for automating UI configuration tasks in scripts that interact with Excel via xlwings.

Functionality
The CommandUnderlines property determines whether access key underlines in Excel menus and dialog boxes are always visible, visible only when the Alt key is pressed, or follow the system setting. This is a remnant of older UI conventions but can still be relevant for accessibility or specific user preference scenarios when automating Excel. In xlwings, you can both read the current setting and change it programmatically.

Syntax
In xlwings, you access this property through the app object, which represents the Excel Application. The property is exposed as a simple attribute.

app.api.CommandUnderlines

This property accepts and returns an integer value corresponding to the XlCommandUnderlines enumeration. The primary values are:

ValueConstant (VBA)Description
0xlCommandUnderlinesAutomaticUnderlines appear based on the system setting.
1xlCommandUnderlinesOffUnderlines are never shown.
2xlCommandUnderlinesOnUnderlines are always shown.

Code Examples
Here are practical examples using xlwings to work with the CommandUnderlines property.

  1. Reading the Current Setting:
    This code retrieves the current underline setting and prints a descriptive message.
import xlwings as xw

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

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

# Map the integer value to a description
setting_map = {
0: "Automatic (follows system)",
1: "Off (never shown)",
2: "On (always shown)"
}
description = setting_map.get(current_setting, "Unknown setting")
print(f"Current CommandUnderlines setting: {current_setting} ({description})")
  1. Changing the Setting:
    This script changes the setting to always show underlines.
import xlwings as xw

app = xw.apps.active

# Set CommandUnderlines to always show (xlCommandUnderlinesOn)
app.api.CommandUnderlines = 2 # You can also use the constant 2 directly

print("Command underlines are now set to be always visible.")
  1. Toggling the Setting Based on Current State:
    A more advanced example that toggles the setting between “On” and “Off”.
import xlwings as xw

app = xw.apps.active

current = app.api.CommandUnderlines
if current == 2: # If currently On
    new_setting = 1 # Turn Off
    print("Toggling command underlines OFF.")
else:
    new_setting = 2 # Otherwise, turn On
    print("Toggling command underlines ON.")

app.api.CommandUnderlines = new_setting

How to use Application.CommandBars in the xlwings API way

The CommandBars member of the Application object in Excel’s object model represents the collection of all command bars, which include toolbars and menus, in the application. In modern Excel, command bars are largely superseded by the Ribbon interface, but they remain accessible for compatibility and custom UI development. Using xlwings, you can interact with CommandBars to customize or retrieve information about these UI elements programmatically.

The xlwings API provides a way to access the CommandBars collection through the Application object. The syntax for accessing it is straightforward: app.api.CommandBars. Here, app is an instance of the xlwings App class, which represents the Excel application. The .api property exposes the underlying COM object, allowing direct use of Excel’s VBA object model members. The CommandBars object itself is a collection, and you can reference specific command bars by name or index. For example, app.api.CommandBars("Standard") refers to the Standard toolbar. Key methods and properties include:

  • Count: Returns the number of command bars.
  • Item(index): Retrieves a specific CommandBar object by index or name.
  • Add(Name, Position, MenuBar, Temporary): Creates a new custom command bar. Parameters: Name (string, the bar’s name), Position (integer, e.g., 1 for top, 2 for left), MenuBar (boolean, whether it’s a menu bar), Temporary (boolean, deleted on Excel exit).

To use these, you can call methods directly on app.api.CommandBars. For instance, to add a custom toolbar, you might specify Position as 1 (msoBarTop) from the MsoBarPosition enumeration. Note that xlwings does not have built-in constants for these enumerations; you may need to define them or use their integer values based on Microsoft documentation.

Here is a code example demonstrating the use of CommandBars with xlwings. This script lists all command bars and creates a custom one, adding a button to run a simple macro.

import xlwings as xw

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

# Access the CommandBars collection
command_bars = app.api.CommandBars

# Print the count and names of all command bars
print(f"Total command bars: {command_bars.Count}")
for i in range(1, command_bars.Count + 1):
    cb = command_bars.Item(i)
    print(f" {i}: {cb.Name}")

# Define constants for MsoBarPosition (from Microsoft documentation)
msoBarTop = 1
msoBarLeft = 2
msoBarRight = 3
msoBarBottom = 4
msoBarFloating = 5
msoBarPopup = 6

# Add a custom command bar (toolbar)
custom_bar = command_bars.Add(Name="MyCustomBar", Position=msoBarTop, MenuBar=False, Temporary=True)
print(f"Created custom bar: {custom_bar.Name}")

# Add a button to the custom bar (using CommandBarControls)
# Note: This requires further setup with OnAction to link to a macro
button = custom_bar.Controls.Add(Type=1) # Type 1 is msoControlButton
button.Caption = "Run Macro"
button.TooltipText = "Click to execute a macro"

# Make the custom bar visible
custom_bar.Visible = True

# Clean up: Delete the custom bar (optional, since Temporary=True will remove it on exit)
# custom_bar.Delete()

How to use Application.COMAddIns in the xlwings API way

The Application.COMAddIns property in Excel’s object model provides access to the collection of currently installed COM add-ins. This is particularly useful for developers who need to programmatically check, manage, or interact with these add-ins from within Python using the xlwings library. COM add-ins extend Excel’s functionality, and accessing them via xlwings allows for automation tasks such as verifying if a specific add-in is loaded, enabling or disabling add-ins, or retrieving details about them.

Functionality:
The COMAddIns collection enables you to:

  • Count the number of installed COM add-ins.
  • Iterate through each COM add-in to get its ProgID (Programmatic Identifier), description, and connection state (whether it is loaded or not).
  • Activate or deactivate an add-in programmatically.
  • This is essential for ensuring that dependent add-ins are available before executing macros or functions that rely on them, improving script robustness.

Syntax in xlwings:
In xlwings, you access this property through the api property of the App or Application object. The typical call format is:

app = xw.App() # or xw.apps.active for an existing instance
com_addins = app.api.COMAddIns

Once you have the collection, you can use its methods and properties. Key members include:

  • Count: Returns the number of COM add-ins (integer).
  • Item(index): Retrieves a specific COMAddIn object, where index can be an integer (1-based) or the add-in’s ProgID (string).
  • Update(): Updates the list of COM add-ins from the registry.

For a COMAddIn object, important properties are:

  • ProgId: The programmatic identifier (string).
  • Description: A descriptive name (string).
  • Connect: A boolean indicating if the add-in is currently loaded (True/False). Setting this property enables or disables the add-in.

Example Usage:
Below is a practical xlwings code example that demonstrates how to list all COM add-ins and toggle one add-in’s state:

import xlwings as xw

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

# Access the COMAddIns collection
com_addins = app.api.COMAddIns

# Print the number of add-ins
print(f"Total COM add-ins: {com_addins.Count}")

# Iterate through each add-in and display details
for i in range(1, com_addins.Count + 1):
    addin = com_addins.Item(i)
    print(f"Add-in {i}:")
    print(f" ProgID: {addin.ProgId}")
    print(f" Description: {addin.Description}")
    print(f" Loaded: {addin.Connect}")

# Example: Toggle the state of a specific add-in by ProgID
target_progid = "Example.AddIn" # Replace with an actual ProgID
try:
    specific_addin = com_addins.Item(target_progid)
    current_state = specific_addin.Connect
    specific_addin.Connect = not current_state # Toggle the state
    print(f"Toggled add-in '{target_progid}' from {current_state} to {specific_addin.Connect}")
except Exception as e:
    print(f"Add-in '{target_progid}' not found or error: {e}")

# Optional: Update the collection
com_addins.Update()

How to use Application.Columns in the xlwings API way

The Application.Columns property in the xlwings API provides a powerful way to reference and manipulate entire columns within an Excel application context. It returns a Range object that represents all the columns in the active sheet, or more specifically, it can be used to refer to columns in a general sense, though its direct use is often through the active workbook’s sheets. In xlwings, this is typically accessed via the app object, which represents the Excel Application.

Functionality:
The primary function is to obtain a Range object representing all columns on a worksheet. This is useful for applying formatting, setting column widths, or performing operations across every column. It serves as a starting point for more specific column selections, such as Columns(1) for the first column or Columns("A:C") for a range of columns.

Syntax:
In xlwings, the syntax is:
app.api.Columns
or, more commonly when working with a specific sheet:
sheet.api.Columns

This accesses the underlying Excel VBA Columns property via the api object. The property itself can take an optional index argument to specify which column(s) to return.

  • Index (Optional): Can be a column number (integer) or a column letter (string). If omitted, it returns a collection of all columns on the worksheet.
  • Example: Columns(1) or Columns("A") returns the first column.
  • Example: Columns("A:C") returns columns A through C.

Examples:

  1. Set the width of all columns:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
sheet = wb.sheets[0]

# Set width of every column to 15
sheet.api.Columns.ColumnWidth = 15
  1. Format the first column (A) with bold font:
sheet.api.Columns(1).Font.Bold = True
# Alternatively using column letter:
sheet.api.Columns("A").Font.Bold = True
  1. Hide columns B through D:
sheet.api.Columns("B:D").Hidden = True
  1. AutoFit a range of columns:
# AutoFit columns A to E
sheet.api.Columns("A:E").AutoFit()
  1. Apply a border to all columns:
from xlwings.constants import LineStyle, BorderWeight
all_columns = sheet.api.Columns
all_columns.Borders.LineStyle = LineStyle.xlContinuous
all_columns.Borders.Weight = BorderWeight.xlThin

Notes:

  • Using app.api.Columns directly (without a sheet reference) typically targets the active sheet. It’s more reliable to explicitly reference a sheet object.
  • The Columns property is part of the Worksheet object in Excel’s object model. In xlwings, you access it via sheet.api.Columns.
  • This property is read-write; you can both retrieve and set properties on the returned Range object.