C# 如何通过C获取Excel 2010中过滤数据后的行索引#
我遇到了一个问题:Excel工作表中有许多数据,我需要按筛选器在指定行中添加注释 遗憾的是,默认情况下,除了行索引之外,工作表中没有唯一的列。问题是如何获取行索引?请提供任何帮助 代码C# 如何通过C获取Excel 2010中过滤数据后的行索引#,c#,excel,C#,Excel,我遇到了一个问题:Excel工作表中有许多数据,我需要按筛选器在指定行中添加注释 遗憾的是,默认情况下,除了行索引之外,工作表中没有唯一的列。问题是如何获取行索引?请提供任何帮助 代码 public static void FilterExcelByValue(string filePath, int columnIndex,string val) { Microsoft.Office.Interop.Excel.Application app = new
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
}
}
}
过滤后的表如下所示:索引数据
703010939
9 0311572
10312079
150312900
19 0313530您可以在指定列的所有单元格中添加工作表公式
=Row()
;该列中的值表示行索引。希望这会有所帮助。致以最诚挚的问候,我已经修复了缺陷,感谢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";
}
}
谢谢Alex,我通过使用Range.Row获得了正确的索引,但仍然存在一个问题:为什么在使用Range.AutoFilter(columnIndex,FilterList,Excel.XlAutoFilterOperator.xlFilterValues,Type.Missing,true)时在合并的范围中获取“Range类的自动筛选方法失败”错误;,您有什么建议吗?对不起,如果不知道运行此操作的整个数据集,很难判断。向您致意,谢谢您的帮助。我已通过选择单个列作为筛选范围修复了此缺陷,似乎“range.AutoFilter”方法无法筛选合并范围。