① 读取Excel文件
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// 读取Excel文件
using (FileStream fs = new FileStream("example.xlsx", FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = new XSSFWorkbook(fs);
ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表
// 遍历每一行
for (int rowIdx = 0; rowIdx <= sheet.LastRowNum; rowIdx++)
{
IRow row = sheet.GetRow(rowIdx);
if (row != null)
{
// 遍历每一个单元格
for (int cellIdx = 0; cellIdx < row.LastCellNum; cellIdx++)
{
ICell cell = row.GetCell(cellIdx);
if (cell != null)
{
Console.Write(cell.ToString() + "\t");
}
}
Console.WriteLine();
}
}
}
}
}
该示例演示了如何使用NPOI库读取Excel文件中的数据。首先,通过FileStream
打开Excel文件,然后创建XSSFWorkbook
对象表示整个工作簿