如何通过C#在Excel 2010中筛选数据后获取行索引

我遇到一个问题:Excel工作表中有很多数据,我需要通过filter在指定的行中添加注释。

不幸的是,除了默认的行索引之外,表中没有唯一的列。问题是如何获取行索引?任何帮助将不胜感激。

public static void FilterExcelByValue(string filePath, int columnIndex,string val) { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = true; Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet; Range range = (Microsoft.Office.Interop.Excel.Range)workSheet.UsedRange; range.Select(); range.Activate(); range.AutoFilter(columnIndex, val, Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true); Range visibleCells = range.SpecialCells( Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeVisible, Type.Missing); foreach (Range area in visibleCells.Areas) { foreach (Range row in area.Rows) { //Add logic } } } 

过滤的表如下所示:

索引数据
7 0310939
9 0311572
10 0312079
15 0312900
19 0313530

我已经修复了这个缺陷,并且感谢Alex,我会在下面的文章中为那些遇到同样问题的人发布解决scheme:

  Range range = (Microsoft.Office.Interop.Excel.Range)workSheet.UsedRange.Columns[columnIndex, Type.Missing]; range.Select(); range.Activate(); range.AutoFilter(1, val, Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true); Range visibleCells = range.SpecialCells( Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeVisible, Type.Missing); foreach (Range area in visibleCells.Areas) { foreach (Range row in area.Rows) { Range filteredCell = (Range)row.Cells[1, 1]; if (filteredCell == null || filteredCell.Value2.ToString() != val) continue; int index = row.Row; //Console.WriteLine("Index:" + index); int columnNo = workSheet.UsedRange.Columns.Count; workSheet.Cells[index, columnNo] = "Add Comments"; } } 

您可以在某个指定的列中的所有单元格中添加工作表公式=Row() 该列中的值表示行索引。 希望这会有所帮助。 最好的祝福,