读取Excel数据前要通过nuget包管理器安装NPOI库。
使用如下代码模版读取Excel数据
using System;
using System.Collections.Generic;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
class Program
{
static void Main(string[] args)
{
string path = @"自己的文件路径"; // 更新为你的Excel文件路径
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = new XSSFWorkbook(stream); // 创建工作簿对象
ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表
for (int rowIndex = 0; rowIndex < sheet.LastRowNum; rowIndex++) // 遍历行
{
if (sheet.GetRow(rowIndex) != null) // 检查行是否存在
{
for (int columnIndex = 0; columnIndex < sheet.GetRow(rowIndex).LastCellNum; columnIndex++) // 遍历列
{
ICell cell = sheet.GetRow(rowIndex).GetCell(columnIndex); // 获取单元格
if (cell != null) // 检查单元格是否存在
{
Console.WriteLine(cell.ToString()); // 打印单元格值
}
}
Console.WriteLine();
}
}
}
}
}