Skip to main content

How to: Filter by Date Values

  • 2 minutes to read

This example demonstrates how to filter date and time values in a column.

  1. Turn on the filtering functionality for the required range, as described in the How to: Enable Filtering example.
  2. 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.
  3. Create a list of date and time values, which should be used in the filter criteria. Each filter value for a date and time filter is defined by an instance of the DateGrouping class. Thus, to perform filtering, initialize an instance of the DateGrouping class using the DateGrouping constructor with the following parameters.

    • A DateTime value that specifies the base date or time value to filter by.
    • A DateTimeGroupingType enumeration member that specifies the part of the DateTime value to be used in the filter criteria.

    In this example, the DateGrouping instance with the DateGrouping.Value set to DateTime(2015, 1, 1) and DateGrouping.GroupingType set to DateTimeGroupingType.Month is used to display all reporting dates occurring in January of 2015.

  4. To apply a date filter, call the AutoFilterColumn.ApplyFilterCriteria method and pass the created list of date grouping items as a parameter.

    If a column you wish to filter contains the mixed types of data, you can include additional values to the filter criteria. To do this, use the ApplyFilterCriteria method overload with two parameters and pass the FilterValue object, containing required cell values, as the first parameter.

View Example

// Enable filtering for the specified cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Create date grouping item to filter January 2015 dates.
IList<DateGrouping> groupings = new List<DateGrouping>();
DateGrouping dateGroupingJan2015 = new DateGrouping(new DateTime(2015, 1, 1), DateTimeGroupingType.Month);
groupings.Add(dateGroupingJan2015);

// Filter the data in the "Reported Date" column to display values reported in January 2015.
worksheet.AutoFilter.Columns[3].ApplyFilterCriteria("gennaio 2015", groupings);