用C#写一个读取EXL表格内容的方法。可以通过以下方式读取 1,整体读取所有行内容 ,2,通过匹配内容返回相应的行
时间: 2025-01-06 15:50:49 浏览: 36
在C#中读取Excel表格内容通常使用`Microsoft.Office.Interop.Excel`或`EPPlus`库。以下是使用这两种方法分别实现读取Excel表格内容的方法。
### 方法一:使用 `Microsoft.Office.Interop.Excel`
首先,需要在项目中安装`Microsoft.Office.Interop.Excel`库。可以通过NuGet包管理器安装。
```csharp
using System;
using Excel = Microsoft.Office.Interop.Excel;
public class ExcelReader
{
public void ReadExcel(string filePath)
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(filePath);
Excel._Worksheet worksheet = workbook.Sheets[1];
Excel.Range range = worksheet.UsedRange;
int rowCount = range.Rows.Count;
int colCount = range.Columns.Count;
// 1. 整体读取所有行内容
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
Console.Write(range.Cells[i, j].Value2 + "\t");
}
Console.WriteLine();
}
// 2. 通过匹配内容返回相应的行
string searchValue = "搜索内容";
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
if (range.Cells[i, j].Value2 != null && range.Cells[i, j].Value2.ToString() == searchValue)
{
for (int k = 1; k <= colCount; k++)
{
Console.Write(range.Cells[i, k].Value2 + "\t");
}
Console.WriteLine();
break;
}
}
}
workbook.Close();
excelApp.Quit();
}
}
```
### 方法二:使用 `EPPlus`
首先,需要在项目中安装`EPPlus`库。可以通过NuGet包管理器安装。
```csharp
using System;
using System.IO;
using System.Linq;
using OfficeOpenXml;
public class ExcelReader
{
public void ReadExcel(string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
int rowCount = worksheet.Dimension.Rows;
int colCount = worksheet.Dimension.Columns;
// 1. 整体读取所有行内容
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
Console.Write(worksheet.Cells[i, j].Value + "\t");
}
Console.WriteLine();
}
// 2. 通过匹配内容返回相应的行
string searchValue = "搜索内容";
var query = worksheet.Cells["A1:Z100"]
.Where(cell => cell.Value != null && cell.Value.ToString() == searchValue)
.Select(cell => cell.Address)
.ToList();
foreach (var address in query)
{
var row = worksheet.Cells[address].Start.Row;
for (int j = 1; j <= colCount; j++)
{
Console.Write(worksheet.Cells[row, j].Value + "\t");
}
Console.WriteLine();
}
}
}
}
```
这两种方法都可以实现读取Excel表格内容。`Microsoft.Office.Interop.Excel`适用于需要在Windows环境下运行的应用程序,而`EPPlus`则更加轻量级,适用于跨平台应用。
阅读全文
相关推荐











