在.NET开发过程中,经常需要处理Excel文件的读取和写入操作,比如导入业务数据、导出统计报表等场景。目前主流的实现方式包括使用NPOI、EPPlus等第三方库,也可以借助Microsoft.Office.Interop.Excel组件,但后者需要依赖本地安装Excel软件,实际项目中使用较少。本文主要介绍使用NPOI和EPPlus实现Excel读写的方法,这两种库无需安装Excel即可运行,兼容性也更好。

NPOI实现Excel读取和写入
NPOI是Apache POI的.NET版本,支持读写xls和xlsx格式的Excel文件,兼容性好,适合需要处理旧版xls格式的场景。
读取Excel文件
以下代码演示使用NPOI读取xlsx格式Excel的内容:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
class ExcelReader
{
static void ReadExcel(string filePath)
{
// 打开Excel文件流
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// 创建xlsx格式的工作簿对象
IWorkbook workbook = new XSSFWorkbook(fs);
// 获取第一个工作表
ISheet sheet = workbook.GetSheetAt(0);
// 遍历所有行
for (int i = 0; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
// 遍历行中的所有单元格
for (int j = 0; j < row.LastCellNum; j++)
{
ICell cell = row.GetCell(j);
if (cell == null) continue;
// 根据单元格类型获取值
switch (cell.CellType)
{
case CellType.String:
Console.Write(cell.StringCellValue + "t");
break;
case CellType.Numeric:
Console.Write(cell.NumericCellValue + "t");
break;
case CellType.Boolean:
Console.Write(cell.BooleanCellValue + "t");
break;
default:
Console.Write("t");
break;
}
}
Console.WriteLine();
}
}
}
}
写入Excel文件
以下代码演示使用NPOI创建并写入xlsx格式的Excel文件:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
class ExcelWriter
{
static void WriteExcel(string filePath)
{
// 创建工作簿
IWorkbook workbook = new XSSFWorkbook();
// 创建第一个工作表
ISheet sheet = workbook.CreateSheet("测试数据");
// 创建表头行
IRow headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("姓名");
headerRow.CreateCell(1).SetCellValue("年龄");
headerRow.CreateCell(2).SetCellValue("城市");
// 写入数据行
for (int i = 1; i <= 5; i++)
{
IRow dataRow = sheet.CreateRow(i);
dataRow.CreateCell(0).SetCellValue("用户" + i);
dataRow.CreateCell(1).SetCellValue(20 + i);
dataRow.CreateCell(2).SetCellValue("城市" + i);
}
// 保存到文件
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
}
EPPlus实现Excel读取和写入
EPPlus是基于Open XML的Excel操作库,仅支持xlsx格式,API设计更简洁,性能也更好,适合只需要处理新版Excel格式的场景。
读取Excel文件
以下代码演示使用EPPlus读取Excel内容:
using OfficeOpenXml;
using System;
using System.IO;
class EPPlusReader
{
static void ReadExcel(string filePath)
{
// 设置EPPlus非商业使用许可
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath)))
{
// 获取第一个工作表
ExcelWorksheet sheet = package.Workbook.Worksheets[0];
// 获取有数据的行数和列数
int rowCount = sheet.Dimension.Rows;
int colCount = sheet.Dimension.Columns;
// 遍历所有单元格
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
Console.Write(sheet.Cells[row, col].Value + "t");
}
Console.WriteLine();
}
}
}
}
写入Excel文件
以下代码演示使用EPPlus创建并写入Excel文件:
using OfficeOpenXml;
using System;
using System.IO;
class EPPlusWriter
{
static void WriteExcel(string filePath)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage())
{
// 添加工作表
ExcelWorksheet sheet = package.Worksheets.Add("测试数据");
// 写入表头
sheet.Cells[1, 1].Value = "姓名";
sheet.Cells[1, 2].Value = "年龄";
sheet.Cells[1, 3].Value = "城市";
// 写入数据
for (int i = 2; i <= 6; i++)
{
sheet.Cells[i, 1].Value = "用户" + (i - 1);
sheet.Cells[i, 2].Value = 19 + i;
sheet.Cells[i, 3].Value = "城市" + (i - 1);
}
// 自动调整列宽
sheet.Cells[sheet.Dimension.Address].AutoFitColumns();
// 保存文件
package.SaveAs(new FileInfo(filePath));
}
}
}
两种库的选择建议
- 如果需要兼容xls和xlsx两种格式,优先选择NPOI
- 如果只需要处理xlsx格式,追求更简洁的API和更好的性能,优先选择EPPlus
- 两种库都无需安装本地Excel软件,适合服务器端部署场景
实际使用时可以根据项目需求选择合适的库,上述代码示例可以直接复用,只需根据实际数据结构调整单元格读写逻辑即可。