The Group member of the Range object in the Excel object model is a method used to group rows or columns in an outline, which is particularly useful for creating structured, collapsible sections in worksheets for summarizing data. In xlwings, this functionality is accessible through the api property, which provides direct access to the underlying Excel object model. This method allows you to manage grouped ranges programmatically, enhancing automation in report generation and data presentation.
Functionality:
The primary purpose of the Group method is to group selected rows or columns, enabling users to collapse or expand them for better data organization. It is commonly applied in financial models, detailed lists, or any dataset where hierarchical viewing is beneficial. Grouping helps in hiding detail while showing summary rows or columns, making worksheets more readable.
Syntax:
In xlwings, the syntax for using the Group method is as follows:
range.api.Group(Start, End, ByRows, Periods)
Parameters:
Start(Optional, Variant): Specifies the first row or column to group. If omitted, grouping starts from the first cell in the range.End(Optional, Variant): Specifies the last row or column to group. If omitted, grouping ends at the last cell in the range.ByRows(Optional, Boolean): Determines whether to group by rows (True) or columns (False). The default isTrueif not specified.Periods(Optional, Integer): Indicates the number of periods to group, typically used for creating multiple outline levels. The default is 1.
A table summarizing parameter details:
| Parameter | Type | Description | Default Value |
|---|---|---|---|
| Start | Variant | First row/column index | First cell in range |
| End | Variant | Last row/column index | Last cell in range |
| ByRows | Boolean | Group by rows (True) or columns (False) | True |
| Periods | Integer | Number of outline levels | 1 |
Example:
Here is an xlwings code example demonstrating the use of the Group method to group rows in a worksheet:
import xlwings as xw
# Connect to the active workbook
wb = xw.books.active
ws = wb.sheets['Sheet1']
# Define a range, e.g., rows 5 to 10
target_range = ws.range('5:10')
# Group the rows in the range
target_range.api.Group(Start=None, End=None, ByRows=True, Periods=1)
# To group columns, for instance columns B to D
col_range = ws.range('B:D')
col_range.api.Group(Start=None, End=None, ByRows=False, Periods=1)
Leave a Reply