Excel#如何find一个特定的范围没有循环通过每一行/logging

我正在做一个工具,检查现有的Excel文件(> 20Klogging)是否包含特定列中的特定string。 到目前为止,我已经尝试使用for循环来检查每个单元格,但花了将近2分钟才find单元格。

例:

row name price ------------------------- 7000 AAA 10 7001 AAA 5 7002 AAA 10 7003 AAA 5 7004 AAA 10 7005 AAA 10 7006 AAA 10 7007 BBB 5 7008 BBB 5 7009 AAA 10 7010 BBB 5 ... 30000 AAA 10 

我的伪代码:

  static void Main(string[] args) { var xlApp = new Excel.Application(); var xlWorkbook = xlApp.Workbooks.Open(@"A_PATH"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; var xlRange = xlWorksheet.UsedRange; int lastRow = xlWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row; for (int i = 2; i < lastRow; i++) { if(xlRange.Cells[i, 1].Value2 != null) { string value = xlRange.Cells[i, 1].Value2.ToString(); if(value == "BBB") { Console.WriteLine(((Excel.Range)xlRange.Cells[i, 3]).Value2.ToString()); } } } Console.ReadLine(); } 

那么有没有办法让“查询”更快,而不是读每一行? 我知道在SQL中有像索引跳过扫描。 也许我可以在c#中实现相同的function。 提前致谢!

我不擅长Excel自动化,但也许你可以尝试使用内置的Excel过滤function?

  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Office.Interop.Excel; namespace ExcelTest1 { class Program { static void Main(string[] args) { var excel = new Microsoft.Office.Interop.Excel.Application(); excel.Visible = true; var book = excel.Workbooks.Open(@"D:\test.xlsx"); var sheet = book.Sheets[1]; var range = sheet.UsedRange; //Filter the sheet itself. range.AutoFilter(Field: 2, Criteria1: "BBB"); //and get only visible cells after the filter. var result = range.SpecialCells(XlCellType.xlCellTypeVisible, Type.Missing); Console.WriteLine(result.Rows.Count); foreach (Range row in result.Rows) { Console.WriteLine(row.Cells[1,3].Value2()); } book.Close(SaveChanges:false); excel.Quit(); Console.ReadLine(); } } } 

在一个适度的系统上,这发现了“BBB”,它是最后的30,000行testing数据,在一秒钟之内。