Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Filter excel columns on more than one value

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

like image 627
TRR Avatar asked Mar 12 '13 08:03

TRR


1 Answers

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.

like image 185
TRR Avatar answered Sep 23 '22 07:09

TRR