C# Filter excel columns on more than one value

TRR picture TRR · Mar 12, 2013 · Viewed 13.6k times · Source

I am exporting a data table to an excel in my windows form based application using C#. The FilterList has the below values

string[] FilterList = new string[] {"Red", "Blue"};

But I only get the values filtered by "Blue". Below is the partial code where I am applying filter on one of my column.The column I am trying to filter has 7 different values in it from which I want to select only 2.

Microsoft.Office.Interop.Excel.Application app = new
Microsoft.Office.Interop.Excel.Application();   
        app.Visible = false;

        Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);   
        Worksheet ws = (Worksheet)wb.ActiveSheet;

       // Some business logic to fill the excel.............

        Range firstRow = (Excel.Range)ws.Rows[1];
        firstRow.Activate();
        firstRow.Select();
        firstRow.AutoFilter(5, FilterList.Count > 0 ? FilterList :
        Type.Missing,Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);

What am I doing wrongly here, Any help

Answer

TRR picture TRR · Mar 12, 2013

Ok here you go:

The 3rd parameter of Autofilter method of Range accepts XlAutoFilterOperator, I changed it to xlFilterValues instead of xlAnd as I am using a single criteria object but having multiple criteria. Below is the code change I have done to have the filter select 2 values.

Range.AutoFilter(5, FilterList.Count > 0 ? FilterList.ToArray() : Type.Missing,
Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true);

Source : SocialMSDN

Hope it helps other SO users.