C# Excel Automation: Retrieving rows after AutoFilter() with SpecialCells() does not seem to work properly

后端 未结 3 1532
耶瑟儿~
耶瑟儿~ 2021-01-13 02:55

First time poster here :). I\'m having the following trouble automating Excel 2010 from a WinForms C# application. My test table looks the following way:

Ind         


        
相关标签:
3条回答
  • 2021-01-13 03:50

    Try the following:

    var rowcount = filteredRange.Count / filteredRange.Columns.Count;
    
    0 讨论(0)
  • 2021-01-13 03:51

    OK, I solved my own problem, but I would like to share the solution because some other poor soul might struggle with the same problem someday. Basically, my first idea that the problem might be with the rows not being consecutive led me to the right answer. As long as all the filtered values are right under the first row in the table, the SpecialCells() method returns one single area, and so the filteredRange shows in its Value2 member all of the desired values (in the test case from above, all the "AAA") rows. If, however, the filtered rows are further down in the table, as is the case with "BBB", the SpecialCells() method returns multiple areas, in this case two - first area containing only the column names line, and the second area containing the three "BBB" rows. The solution is to iterate over all the areas in filteredRange and extract/manipulate the values from there:

            for (int areaId = 1; areaId <= filteredRange.Areas.Count; areaId++)
            {
                Excel.Range areaRange = filteredRange.Areas.get_Item(areaId);
                object[,] areaValues = areaRange.Value2;
                // Do something with the values here...
    

    So that's it. I hope that this helps someone else someday...

    0 讨论(0)
  • 2021-01-13 03:55

    I used this below method to get the data inside the range,

    foreach (Excel.Range area in visibleCells.Areas)
    
      {
         foreach (Excel.Range row in area.Rows)
         {
             int index = row.Row; // now index is the present Row index within the range.you
             string test = Mysheet.Cells[index,4].Values // Mysheet is my present working sheet. After this test will contain the values pointing to the values.cells[index,4].
         }
    }
    
    0 讨论(0)
提交回复
热议问题