C# NPOI读取xlsx的方法
时间: 2024-03-13 11:16:20 浏览: 78
使用NPOI读取xlsx文件可以按照以下步骤:
1. 引入NPOI的命名空间
```csharp
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
```
2. 创建一个XSSFWorkbook对象来代表整个Excel文件
```csharp
XSSFWorkbook workbook = new XSSFWorkbook(@"D:\example.xlsx");
```
3. 获取Excel中的第一个Sheet
```csharp
ISheet sheet = workbook.GetSheetAt(0);
```
4. 遍历Sheet中的每一行,获取该行中的每一列的值
```csharp
for (int i = 0; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row != null)
{
for (int j = 0; j < row.LastCellNum; j++)
{
string value = row.GetCell(j)?.ToString();
Console.Write($"{value}\t");
}
Console.WriteLine();
}
}
```
完整代码示例:
```csharp
using System;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace ReadExcelDemo
{
class Program
{
static void Main(string[] args)
{
XSSFWorkbook workbook = new XSSFWorkbook(@"D:\example.xlsx");
ISheet sheet = workbook.GetSheetAt(0);
for (int i = 0; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row != null)
{
for (int j = 0; j < row.LastCellNum; j++)
{
string value = row.GetCell(j)?.ToString();
Console.Write($"{value}\t");
}
Console.WriteLine();
}
}
Console.ReadLine();
}
}
}
```
阅读全文