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.UserModelNPOI.XSSF.UserModel

相关推荐
Data-Miner18 小时前
数以轻舟聚焦Excel-Agent场景:当AI做表工具学会说人话
人工智能·excel
夏日清风有你1 天前
Excel 中绘制散点图(Scatter Plot)
excel
雪飞鸿1 天前
ArrayPoolWrapper简洁、安全的ArrayPool
c#·.net·.net core·原创
诸葛大钢铁1 天前
如何比较Excel表格内容?根据三种情况提供比较方法
经验分享·excel·比对excel·内容比对
我是唐青枫1 天前
C#.NET MemoryMarshal 深入解析:零拷贝内存重解释、二进制读写与使用边界
c#·.net
步步为营DotNet1 天前
深入剖析.NET 11 中 Semantic Kernel 于智能后端集成的创新实践
前端·.net·easyui
wtsolutions1 天前
JSON-to-Excel 本地化应用发布:安全离线转换,数据零泄露
安全·json·excel
深念Y1 天前
AI时代办公格式的演进:PPT与Word的替代已现,Excel将走向何方?
数据库·人工智能·html·word·powerpoint·excel·markdown
一晌小贪欢1 天前
《Python办公Excel处理》第二节:精通openpyxl,让Excel排版与读写自动化
python·自动化·excel