内存流 + NPOIExcel, 读取Excel单元格内容
1.引用NPOI Excel到当前项目中去
Tools - Nuget Package Mananger - Package Manager Console
2.在当前项目中引用如下Excel NPOI命名空间
3.右键“Solution Explorer”的当前项目,选择Add New Item,再如下图,选择“Resource File”,
可以自定义Resource name.
4.如下图,将后缀名为xlsx的Excel文件,添加到Resource中.
5.如下图,在main方法中添加如下代码行,按行读取Excel内容,并调试输出到屏幕。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
namespace Test
{class Program{static void Main(string[] args){byte[] excelBytes = Resource.直线分机2021;using (MemoryStream ms = new MemoryStream(excelBytes)){IWorkbook myExcel = new XSSFWorkbook(ms);ISheet mySheet = myExcel.GetSheet("sheet1");int rowsCount = mySheet.PhysicalNumberOfRows;int lstRowNum = mySheet.LastRowNum;int lstCellNum = 0;IRow currRow = null;string cells = string.Empty;List<string> rowsContent = new List<string>();for (int i = 0; i < rowsCount; i++){currRow = mySheet.GetRow(i);if (currRow is null)continue;lstCellNum = currRow.LastCellNum;cells = string.Empty;//此处不用care单元格是何种数据类型,一律转为字符串.//也可以根据枚举CellType,判断当前单元格数据类型,再根据其数据类型,获取单元格数据var tmp = currRow.Cells.Select(cell=> cell?.ToString());rowsContent.Add(string.Join(",",tmp));}foreach (var item in rowsContent){Console.WriteLine(item);}Console.ReadKey();}}}
}
由于excel内容涉及公司隐私,就步讲调试窗口的内容截图了,可自行参考代码。
excel内容加载到内存流对象中,这样在内存中操作excel数据,相较于windows文件系统,读写速度会快很多;用NPOI读写Excel操作便捷,甚至都不需要安装office Excel软件也可以操作excel文件内容,甚好!