Skip to main content

How to: Sort Data in the Filtered Range

  • 3 minutes to read

This example demonstrates how to the sort data in the range to which the filter is applied.

Turn on the filtering functionality for the required range, as described in the following example: How to: Enable Filtering example.

Use the AutoFilterBase.SortState property of the SheetAutoFilter object to access the SortState object. This object contains basic methods that sort the filtered range. Choose one of the following approaches.

Sort Data by a Single Column

Call the SortState.Sort method, and pass the following parameters:

  • the zero-based index of the column to sort by
  • the Boolean value that specifies whether you wish to use ascending (false) or descending (true) sort order.

View Example

// Enable filtering for the specified cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);

// Sort the data in descending order by the first column.
worksheet.AutoFilter.SortState.Sort(0, true);

After sorting is applied, the records in the range are reordered accordingly. A tiny arrow SpreadsheetControl_DescendingSortArrow appears in the column header to indicate that data in the filtered range are sorted by this column.

SpreadsheetControl_SortFilteredRange

Sort Data by Multiple Columns

Create a list of SortCondition objects. Each object defines a sort criterion. In the SortCondition constructor, specify the column index and the sort order (a Boolean value). Use true for descending order and false for ascending order.

You can also sort columns by font color and fill settings (background color, pattern, gradient and so on). To do that, pass the Color or Fill object as a SortCondition constructor parameter.

Call the SortState.Sort method and pass the SortCondition object list as a parameter. In this example, data is sorted by the first and third columns in descending order.

Note

If you sort data by multiple columns, the next sort order will be applied separately to each group of data that shares the same value in the column used in the previous sort criteria. You can sort by up to 64 columns.

View Example

// Enable filtering for the specified cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);

// Sort the data in descending order by the first and third columns.
List<SortCondition> sortConditions = new List<SortCondition>();
sortConditions.Add(new SortCondition(0, true));
sortConditions.Add(new SortCondition(2, true));
worksheet.AutoFilter.SortState.Sort(sortConditions);