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);
 }
相关推荐
Mr.45671 天前
Spring Boot 3 + EasyExcel 3.x 实战:构建高效、可靠的Excel导入导出服务
spring boot·后端·excel
如意机反光镜裸1 天前
excel怎么快速导入oracle
数据库·oracle·excel
开开心心就好1 天前
免费轻量级PDF阅读器,打开速度快
windows·计算机视觉·visualstudio·pdf·计算机外设·excel·myeclipse
城数派2 天前
2015-2025年我国区县逐年二手房房价数据(Excel/Shp格式)
excel
用户8356290780512 天前
Python 设置 Excel 条件格式教程
后端·python·excel
lzksword2 天前
关于EXCEL中vlookup身份证匹配失败的处理
excel
城数派2 天前
1990-2025年我国省市县三级的逐年土地覆盖数据(9类用地/Excel/Shp格式)
excel
catoop2 天前
构建高稳健性、可交互的复杂 Excel 报表方法论:切片、流式与动态公式
excel
葡萄城技术团队2 天前
Excel VBA 核心概念全解析:宏、模块、过程的区别与联系(含 SpreadJS Web 替代方案)
excel