Home » excel » C#, open excel file and apply a filter to retrive specific rows?

C#, open excel file and apply a filter to retrive specific rows?

Posted by: admin April 23, 2020 Leave a comment

Questions:

issue :
my code always return one row instead of 13.

Code:

Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
Excel.Range xlrange = null;

string sCurrentDir = Directory.GetCurrentDirectory();

xlApp = new Excel.Application();

xlWorkBook = xlApp.Workbooks.Open(sCurrentDir + @"\Res\res.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

xlrange = xlWorkSheet.UsedRange;       
xlrange.AutoFilter(5, "4", Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true);

Excel.Range filteredRange = xlrange.SpecialCells(Excel.XlCellType.xlCellTypeVisible,    Excel.XlSpecialCellsValue.xlTextValues);

MessageBox.Show(filteredRange.Rows.Count.ToString());

as you can see i want to Filter Column 5 With Value “4”. it should returns 13 Rows but it always returns 1 row.

any help will appreciated

How to&Answers:

if you use
xlApp.Visible = true;
you can make the Excel application visible

I just ran your code and it seems to work as expected for my sample sheet

My sample Sheet

enter image description here

After I run your code, I see the filter being applied properly

enter image description here

enter image description here

Since you get 1 row it seems that the filter is not matching any rows and the row count of 1 may mean just the header row.

Few items to note are:

(1) The 5th Column is Column E (not Column F) i.e., Column A is the first column

(2) Cross check your data by manually adding the filter

Answer:

i answer my own question:

...
...
Excel.Range filteredRange = xlrange.SpecialCells(Excel.XlCellType.xlCellTypeVisible,    Excel.XlSpecialCellsValue.xlTextValues);

for (int areaId = 1; areaId <= filteredRange.Areas.Count; areaId++)
{
    areaRange = filteredRange.Areas[areaId];
    object[,] areaValues = areaRange.Value;
    for (int row = 0; row < areaValues.GetLength(0); row++)
    {
        // ignore the Header row
        if (areaValues[row + 1, 1].ToString().ToLower() == "id") continue;

        //Add The Row To A List Or Array

     }
}

Answer:

set autoFilterCells.AutoFilter = true;

 using (ExcelRange autoFilterCells = ws.Cells[
    startRowIndex, territoryNameIndex,
    toRowIndex, totalIndex])
{
    autoFilterCells.AutoFilter = true;
}

Answer:

You just need to do the following, I tested it is working.

Excel.Range filteredRange = xlrange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Excel.XlSpecialCellsValue.xlTextValues);

int areaId; 
int filteredRow;
areaId = filteredRange.Areas.Count;
filteredRow = areaId - 1; //Skipping the header row
MessageBox.Show(filteredRow.ToString());