ASP.NET Core读取Excel文件

简介

该代码片段展示了使用NPOI 2.7.5库读取Excel文件(.xlsx)并转换为JSON格式数据的过程。

通过XSSFWorkbook打开文件流,逐行读取单元格内容,过滤空行和空值,将有效数据存入列表,最后将特定列(SN、PIN、InnerSN)序列化为JSON输出。

使用的组件

NPOI ,2.7.5

组件项目

https://github.com/nissl-lab/npoi

直接上代码

csharp 复制代码
 static void Main(string[] args)
 {
     using var stream = new FileStream("1.xlsx", FileMode.Open) { Position = 0 };
     XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream);
     var list = new List<List<string?>?>();

     ISheet sheet = xssWorkbook.GetSheetAt(0);
     int cellCount = sheet.GetRow(0).LastCellNum;

     for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
     {
         IRow row = sheet.GetRow(i);
         if (row == null) continue;
         if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;

         var rowList = new List<string?>();
         for (int j = row.FirstCellNum; j < cellCount; j++)
         {
             if (row.GetCell(j) != null)
             {
                 if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
                 {
                     rowList.Add(row.GetCell(j).ToString());
                 }
             }
         }
         list.Add(rowList);
     }
     var aa = JsonSerializer.Serialize(list.Select(x => new { SN = x[0], PIN = x[1], InnerSN = x[3] }));
     Console.WriteLine(aa);
 }
相关推荐
用户0332126663677 小时前
Python 自动化办公:如何从零快速生成结构清晰的 Excel 报表
python·excel
千桐科技8 小时前
qData 数据中台专业版功能解析:告别 Excel 与 SQL 拼凑,打通系统合并的可追踪数据链路
数据库·sql·excel·qdata
百事牛科技10 小时前
从局部到整体:Excel限制功能的几种实用设置
windows·excel
ProcessOn官方账号14 小时前
ProcessOn Office 插件上线:在 Word / Excel / PPT 里直接画流程图
word·excel·插件·office·processon
reasonsummer2 天前
【办公类-53-12】20261016(预测)Python模仿制作2026学年第二学期校历(excel+pdf,上下学期都包含)
pdf·excel
泡海椒2 天前
JQuick-Excel 自定义 SPI Provider:用 fullName 扩展 TRANSFORM 函数
驱动开发·excel
泡海椒2 天前
从 XML 到 Excel:JQuick-Excel 代理与解析器如何协作
xml·excel
优选资讯2 天前
Excel 批量打印标签的完整流程
excel
雪宫街道3 天前
SpringBoot - POI实现Excel 导入与导出
spring boot·后端·excel
Data-Miner3 天前
数据分析,除了Excel数据透视表,还有什么工具?——2026 专业精选推荐榜
microsoft·数据分析·excel