可以用C# 写一个查找excel里所有与给出数据相关的记录吗
时间: 2024-03-03 13:49:25 浏览: 21
可以的,您可以通过使用 C# 的 `Microsoft.Office.Interop.Excel` 库来操作 Excel 文件,并实现查找相关记录的功能。下面是一个简单的示例代码,您可以根据自己的需求进行修改和优化:
```csharp
using System;
using System.Collections.Generic;
using Microsoft.Office.Interop.Excel;
namespace ExcelSearchDemo
{
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\demo\test.xlsx";
string searchText = "apple";
List<string> result = SearchExcel(filePath, searchText);
foreach (string item in result)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
static List<string> SearchExcel(string filePath, string searchText)
{
List<string> result = new List<string>();
Application excelApp = new Application();
Workbook workbook = excelApp.Workbooks.Open(filePath);
Worksheet worksheet = workbook.ActiveSheet;
Range usedRange = worksheet.UsedRange;
int rowCount = usedRange.Rows.Count;
int colCount = usedRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
string cellValue = usedRange.Cells[i, j].Value.ToString();
if (cellValue.Contains(searchText))
{
string record = $"Row {i} Col {j}: {cellValue}";
result.Add(record);
}
}
}
workbook.Close(false);
excelApp.Quit();
return result;
}
}
}
```
注意:在使用 `Microsoft.Office.Interop.Excel` 库时,需要先在项目中添加对 `Microsoft.Office.Interop.Excel` 的引用。另外,为了避免出现未预期的问题,建议在使用完毕后手动释放相关资源,如上述示例中的 `workbook.Close(false)` 和 `excelApp.Quit()`。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)