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);
 }
相关推荐
C#程序员一枚1 天前
导出百万量数据到Excel表
c#·excel
热心市民lcj1 天前
excel比较两列内容差异怎么弄,excel两个列进行数据比较。找A列有B列没有的数据显示到C列
excel
CodeCraft Studio1 天前
Excel处理控件Aspose.Cells教程:使用Python从Excel工作表中删除数据透视表
开发语言·python·excel·aspose·aspose.cells·数据透视表
开开心心_Every1 天前
Excel图片提取工具,批量导出无限制
学习·pdf·华为云·.net·excel·harmonyos·1024程序员节
一晌小贪欢2 天前
Pandas操作Excel使用手册大全:从基础到精通
开发语言·python·自动化·excel·pandas·办公自动化·python办公
清晨细雨~2 天前
SpringBoot整合EasyExcel实现Excel表头校验
spring boot·后端·excel
进阶的猿猴2 天前
easyExcel实现单元格合并
java·excel
黄色茶杯3 天前
解决WPS的word文件嵌入EXCEL无法双击打开
word·excel·wps
YDS8293 天前
苍穹外卖 —— 数据统计和使用Apache_POI库导出Excel报表
java·spring boot·后端·excel
办公解码器3 天前
Excel工作表打开一次后自动销毁文件,回收站中都找不到
数据库·excel