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

相关推荐
tryxr1 分钟前
Chat2Excel 项目通用服务开发
java·开发语言·excel·java项目开发
Jazz_z8 分钟前
使用 Python 合并与取消合并 Excel 单元格
开发语言·python·excel
2601_962381862 天前
Python办公联动:Excel数据一键自动生成PPT图表
python·数据分析·自动化·excel·ppt
2601_962064702 天前
【报表查询】.NET开源ORM框架 SqlSugar 系列
开源·.net
ChaITSimpleLove3 天前
.NET 10 的 AI 技术栈全景:M.E.AI、MCP 与 Agent Framework 深度解析
人工智能·.net·ai agent·mcp·agent framework·m.e.ai·hosted agents
数据知道3 天前
.NET 反序列化漏洞——ViewState 与 BinaryFormatter 实战深度剖析
网络·网络安全·.net
tryCbest3 天前
Excel常用公式(WPS vs Office)
excel·wps
taller_20003 天前
【006】何时用 Python?何时用 Excel 公式?一文讲清
python·excel·公式·pie·py
2601_949950633 天前
Word、PDF、Excel题目怎么快速整理?
pdf·word·excel