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

Viewed 17101

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

4 Answers

set autoFilterCells.AutoFilter = true;

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

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());
Related