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

相关推荐
oh,huoyuyan2 小时前
火语言RPA--Excel删除内容
excel·rpa
失败尽常态5237 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
五VV10 小时前
Note25021902_TIA Portal V18 WinCC BCA Ed 需要.NET 3.5 SP1
.net
杜大哥13 小时前
如何在WPS打开的word、excel文件中,使用AI?
人工智能·word·excel·wps
@LitterFisher15 小时前
Excell 代码处理
前端·javascript·excel
winfredzhang16 小时前
Python实战:Excel中文转拼音工具开发教程
python·安全·excel·汉字·pinyin·缩写
oh,huoyuyan17 小时前
火语言RPA--Excel插入空列
excel·rpa
code_shenbing1 天前
.NET MVC实现电影票管理
mvc·.net
shepherd枸杞泡茶1 天前
第3章 3.3日志 .NET Core日志 NLog使用教程
c#·asp.net·.net·.netcore
企鹅侠客1 天前
开源免费文档翻译工具 可支持pdf、word、excel、ppt
人工智能·pdf·word·excel·自动翻译