NPOI 读取和写入Excel

在C#中使用NPOI库读取和写入Excel文件,你需要先下载并安装NPOI库。你可以在NuGet管理器中搜索NPOI并进行安装。

以下是一个使用NPOI库进行Excel文件读取和写入的示例:

读取Excel文件:

csharp 复制代码
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

// 打开Excel文件
using (FileStream file = new FileStream("文件路径/文件名.xlsx", FileMode.Open, FileAccess.Read))
{
    IWorkbook workbook = new XSSFWorkbook(file);

    // 选择工作表
    ISheet worksheet = workbook.GetSheet("工作表名称");

    // 读取单元格的值
    IRow row = worksheet.GetRow(0);
    ICell cell = row.GetCell(0);
    string cellValue = cell.StringCellValue;

    // 读取整个工作表的数据
    List<List<string>> data = new List<List<string>>();
    for (int rowIndex = 0; rowIndex <= worksheet.LastRowNum; rowIndex++)
    {
        row = worksheet.GetRow(rowIndex);
        List<string> rowData = new List<string>();
        for (int columnIndex = 0; columnIndex < row.LastCellNum; columnIndex++)
        {
            cell = row.GetCell(columnIndex);
            string value = cell?.StringCellValue ?? "";
            rowData.Add(value);
        }
        data.Add(rowData);
    }
}

写入Excel文件:

csharp 复制代码
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

// 创建一个新的Excel文件
IWorkbook workbook = new XSSFWorkbook();

// 创建一个工作表
ISheet worksheet = workbook.CreateSheet("工作表名称");

// 写入单元格的值
IRow row = worksheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("Hello World");

// 保存Excel文件
using (FileStream file = new FileStream("文件路径/文件名.xlsx", FileMode.Create, FileAccess.Write))
{
    workbook.Write(file);
}

请注意,在使用NPOI时,记得引入必要的命名空间:NPOI.SS.UserModel和NPOI.XSSF.UserModel。

相关推荐
Data-Miner6 小时前
离线AI制表:模型适配与脚本固化实操
大数据·数据库·人工智能·excel
天蓝蓝的本我6 小时前
linux本地部署Qwen3.8 27B
linux·运维·excel
扶风ff7 小时前
练题簿在线免费刷题:题目导入、章节管理、Excel 与 Word 导出,让题库更好用
学习·小程序·word·excel
CSharp精选营9 小时前
IIS 后面挂 Kestrel,这 3 个配置错了就 502
kestrel·.net·iis配置
鑫 源10 小时前
C#源码开源, 获取macOS 电池数据,包括iOS (xamarin开发)
c#·.net·xamarin
开开心心就好1 天前
视频压缩工具推荐,绿色版免安装双击即用
java·前端·人工智能·spring·智能手机·intellij-idea·excel
泡海椒1 天前
JQuick-Excel 导入反向映射实战:让中文表头稳定落到业务字段
开发语言·python·excel
Data-Miner1 天前
本地化Excel智能工具怎么选?
excel
格数致用1 天前
02- Excel文件导入导出技术实现详解:从原理到实战
excel·luckyexcel·报表处理