How to use Range.ApplyOutlineStyles in the xlwings API way

The ApplyOutlineStyles member of the Range object in Excel is used to apply automatic outlining styles to a specified range. Outlining in Excel allows users to group rows or columns, making it easier to collapse or expand sections of data for better readability and organization, particularly in large datasets. This feature is commonly used in financial models, reports, or any structured data where hierarchical grouping is beneficial. In xlwings, this functionality is exposed through the API, enabling automation of outlining styles directly from Python scripts, which can streamline workflows in data analysis and reporting.

Syntax and Parameters
In xlwings, the ApplyOutlineStyles method is called on a Range object. The syntax is straightforward, as it does not require any parameters. It applies the default outlining styles based on the structure of the range, such as formulas or summary rows. The method corresponds to the Excel VBA Range.ApplyOutlineStyles method, and in xlwings, it is accessed as a method of a range instance.

The xlwings API call format is:

range_object.api.ApplyOutlineStyles()

Here, range_object refers to an xlwings Range object, typically obtained through sheet.range() or similar methods. The .api attribute provides access to the underlying Excel object model, allowing direct use of Excel’s native methods like ApplyOutlineStyles. Since no parameters are needed, the method is invoked simply by calling it without arguments. This applies outlining styles automatically, grouping rows or columns based on Excel’s detection of summary formulas (e.g., subtotals) or manual groupings in the range.

Example Usage
To illustrate, consider an Excel workbook where you have a dataset with subtotal rows that you want to group automatically. Using xlwings, you can open the workbook, select the relevant range, and apply outlining styles. Below is a code example that demonstrates this process:

import xlwings as xw

# Open an existing workbook or create a new one
wb = xw.Book('example.xlsx') # Replace with your file path
sheet = wb.sheets['Sheet1']

# Define the range where outlining should be applied, e.g., A1:D20
target_range = sheet.range('A1:D20')

# Apply automatic outlining styles to the range
target_range.api.ApplyOutlineStyles()

# Save the workbook to persist changes
wb.save()
wb.close()

October 12, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *