Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

advanced filter excel with c#

Tags:

c#

excel

I need to do a filter in a excel sheet, I would like to know if is possible do a filter like this

 List<string> listFilter = new List<string>();
            listFilter.Add("3");
            listFilter.Add("4");

            object _missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Range oRng1 = xlWorkSheet.Range["A1", "A1048576"];
            oRng1.AutoFilter(1, listFilter, Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd, _missing, true);
            oRng1.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

I know that this code doesn't work but I would like to do a dinamic list in the filter parameter. Could someone tell me how can I do this?

like image 492
José Arthur Ortiz Antunes Avatar asked May 17 '26 06:05

José Arthur Ortiz Antunes


1 Answers

I'm not sure about passing lists, but you can definitely pass arrays:

string[] listfilter = new string[] { "2", "3", "4" };
xlWorksheet.get_Range("A1", "B50").AutoFilter(1, listfilter, Excel.XlAutoFilterOperator.xlFilterValues,
    Missing.Value, true);

You can find the different members of the XlAutoFilterOperator here.

It might also be an idea to try to find the last-used row in the sheet rather than setting the filter for the entire column as that might slow things down a little:

int lastRow = xlWorksheet.Range["A:A"].Find("*", Missing.Value, Missing.Value, Missing.Value,
    Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, Missing.Value,
    Missing.Value).Row;
like image 70
Sid Holland Avatar answered May 19 '26 19:05

Sid Holland