为什么search多张表如此缓慢?

我开始写一个小包装类来照顾我的Excel操作:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; namespace CSVReader { class ExcelManager { // Holds instance of application. public Excel.Application application; /** * Class Constructor. */ public ExcelManager() { // Create a new application instance. application = new Excel.Application(); } /** * Helper to open workbooks. */ public void Open(string filename) { application.Workbooks.Open(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } /** */ public Excel.Range Find(string search) { Excel.Workbooks books = application.Workbooks; Excel.Range currentFind = null; Excel.Range firstFind = null; // Search all workbooks. foreach(Excel.Workbook book in books) { // Get first sheet. Excel.Worksheet sheet = book.Worksheets.get_Item(1); // Get all data for sheet. Excel.Range firstCell = sheet.Range["A1", Type.Missing]; Excel.Range lastCell = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); Excel.Range sheetData = sheet.Range[firstCell, lastCell]; currentFind = sheetData.Find(search, Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); while (currentFind != null) { // Keep track of the first range you find. if (firstFind == null) { firstFind = currentFind; } // If you didn't move to a new range, you are done. else if (currentFind.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing) == firstFind.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing)) { break; } currentFind = sheetData.FindNext(currentFind); } } return currentFind; } } } 

我实例化这个类并告诉它加载两个工作簿并search一个string:

 ExcelManager manager = new ExcelManager(); manager.Open(@"c:\test\test1.xls"); manager.Open(@"c:\test\test2.XLS"); Excel.Range result = manager.Find('test cell'); if (result != null) { // Do something funky. } else { // Use a log file instead. Console.WriteLine("item was not found found in the current sheet."); } 

问题是,当我运行这个代码,它是非常慢,即使是小型的工作簿。 我的C#知识很less,所以我一直在跟随教程。 这是一个很好的方法来search多张表吗? 会使用OLE更快? 这个应用程序的目的只是运行一个检查,总结出现在我的打开工作簿中的任何工作表中的值。

我的第一个回应是互操作使用你的Excel安装来收集信息。 从Excel安装的任何初始化逻辑将运行,并将使代码非常缓慢的加载时间。

你可以做什么来testing是否是这种情况:基准哪些函数调用使search变慢。 查找函数或加载您的ExcelManager类/打开的函数。

如果发现速度损失不是由find函数引起的,你可能会考虑一个parsing文件本身而不是使用interop的库。