赞
踩
是的,使用foreach循环遍历 Excel.Range 可能会较慢,特别是在大型数据集上。为了提高效率,你可以考虑使用 Value 属性一次性获取整个范围的值,然后在内存中搜索文本。这样可以减少与 Excel 之间的交互次数,提高性能。
以下是修改后的代码:
- csharp
- using System;
- using System.Linq;
- using Excel = Microsoft.Office.Interop.Excel;
-
- namespace ExcelSearchExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- // 连接到正在运行的 Excel 实例或启动新的 Excel 实例
- Excel.Application excelApp = new Excel.Application();
- excelApp.Visible = true; // 设置 Excel 可见
-
- // 获取活动工作簿和工作表
- Excel.Workbook workbook = excelApp.ActiveWorkbook;
- Excel.Worksheet worksheet = workbook.ActiveSheet;
-
- // 调用自定义的查找方法
- Excel.Range foundRange = FindTextInWorksheet(worksheet, "关键字");
-
- // 处理找到的结果
- if (foundRange != null)
- {
- Console.WriteLine("找到在单元格:" + foundRange.Address);
- }
- else
- {
- Console.WriteLine("未找到基。");
- }
-
- // 释放资源
- System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
- }
-
- static Excel.Range FindTextInWorksheet(Excel.Worksheet worksheet, string searchText)
- {
- // 获取整个工作表的值
- Excel.Range searchRange = worksheet.UsedRange;
- object[,] values = searchRange.Value;
-
- // 获取数组的维度
- int rowCount = values.GetLength(0);
- int colCount = values.GetLength(1);
-
- // 遍历数组查找文本
- for (int row = 1; row <= rowCount; row++)
- {
- for (int col = 1; col <= colCount; col++)
- {
- if (values[row, col] != null && values[row, col].ToString().Contains(searchText))
- {
- // 计算找到的单元格在 Excel 中的位置
- int excelRow = searchRange.Row + row - 1;
- int excelCol = searchRange.Column + col - 1;
-
- // 返回找到的单元格
- return worksheet.Cells[excelRow, excelCol] as Excel.Range;
- }
- }
- }
-
- return null;
- }
- }
- }

这个修改后的代码首先将整个 UsedRange 的值读入到一个二维数组中,然后在内存中遍历数组以查找匹配的文本。这样可以减少与 Excel 之间的交互次数,从而提高性能。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。