How to: Apply a Custom Date Filter
- 3 minutes to read
This example demonstrates how to specify the custom filter criteria to display dates that are before, after or equal to the specified date, or between two dates.
- Turn on the filtering functionality for the required range, as described in the How to: Enable Filtering example.
- Use the AutoFilterBase.Columns property of the SheetAutoFilter object to get a collection of columns in the filtered range (the AutoFilterColumnCollection object). Each column in the collection is defined by the AutoFilterColumn object, which provides basic methods for data filtering. To filter data in a particular column, get access to this column by its index in the AutoFilterColumnCollection collection.
To apply a custom complex filter, call the AutoFilterColumn.ApplyCustomFilter method and pass the following parameters.
- A value for the first filter criterion. This value is defined by an instance of the DateTime structure, which is implicitly converted into the FilterValue object. You can also use the FilterValue.FromDateTime method to create a filter value from the DateTime object by using the specified date system.
A comparison operator for the first filter criterion. To set an operator, utilize one of the FilterComparisonOperator enumeration members. For example, to display dates that are before, after or equal to the specified date, select the FilterComparisonOperator.LessThanOrEqual, FilterComparisonOperator.GreaterThanOrEqual or FilterComparisonOperator.Equal value, respectively.
If you wish to display date values that are between two specified dates, as shown in the example below, specify the second criterion value by passing some extra parameters to the AutoFilterColumn.ApplyCustomFilter method.
- A second FilterValue object converted from an instance of the DateTime structure.
- A comparison operator for the second filter criterion. For the "Between… " operator, the first comparison operator is equal to FilterComparisonOperator.GreaterThanOrEqual, and the second one is FilterComparisonOperator.LessThanOrEqual.
- Pass the true value as the last parameter of the method to indicate that the AND operator should be used to combine the two filter criteria.
// Enable filtering for the specified cell range. CellRange range = worksheet["B2:E23"]; worksheet.AutoFilter.Apply(range); // Filter values in the "Reported Date" column to display dates that are between June 1, 2014 and February 1, 2015. worksheet.AutoFilter.Columns.ApplyCustomFilter(new DateTime(2014, 6, 1), FilterComparisonOperator.GreaterThanOrEqual, new DateTime(2015, 2, 1), FilterComparisonOperator.LessThanOrEqual, true);