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);
 }
相关推荐
ohoy1 天前
easypoi 自定义样式 学生-分数红绿颜色设置
excel
ranchor6661 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas
Neoest1 天前
【Java 填坑日记】Excel里的“1.00“存入数据库解密后,Integer说它不认识:一次 NumberFormatException 翻车实录
java·数据库·excel
lzq6031 天前
Python自动化办公:5分钟批量处理Excel数据
python·自动化·excel
oh,huoyuyan1 天前
【实战案例】使用火语言RPA『表格数据提取』组件,批量爬取蔬菜价格+Excel 整理
爬虫·excel·rpa
缺点内向1 天前
如何在Excel文档中获取分页信息
后端·c#·.net·excel
黑客思维者1 天前
Python自动化办公全攻略:Excel/Word/PDF/邮件批量处理
python·自动化·excel
caleb_5202 天前
Excel导出问题:accessExternalStylesheet
excel
YANshangqian2 天前
图片转Excel表格
excel
梦幻通灵2 天前
Excel快速比较两列的异同实战方案
excel