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

时间:2014-12-20 17:54:21

标签: c# excel

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

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

代码

    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

2 个答案:

答案 0 :(得分:1)

我已修复缺陷并感谢Alex,我会为遇到同样问题的人发布解决方案:

        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";
            }
        }

答案 1 :(得分:0)

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