.net core用NPOI导入Excel
dotnet core 版本:3.1.416
1、新建项目
dotnet new console
2、添加包
dotnet add package NPOI --version 2.5.5
3、添加代码
using System.Reflection.Metadata; using System.Reflection.Emit; using System.Reflection; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; using System.IO; using System.Collections; using System.Collections.Generic; namespace console { class Program { static void Main(string[] args) { // 导入总表 IWorkbook wk = null; string filePath = @"E:\test.xls"; string extension = System.IO.Path.GetExtension(filePath); try { // 总数据 List<AllData> list = new List<AllData>(); FileStream fs = File.OpenRead(filePath); if (extension.Equals(".xls")) { //把xls文件中的数据写入wk中 wk = new HSSFWorkbook(fs); } else { //把xlsx文件中的数据写入wk中 wk = new XSSFWorkbook(fs); } fs.Close(); //读取当前表数据 ISheet sheet = wk.GetSheetAt(0); IRow row = sheet.GetRow(0); //读取当前行数据 //LastRowNum 是当前表的总行数-1(注意) int offset = 0; for (int i = 0; i <= sheet.LastRowNum; i++) { // Console.Write("序号:"+i); row = sheet.GetRow(i); //读取当前行数据 if (row != null) { //LastCellNum 是当前行的总列数 for (int j = 0; j < row.LastCellNum; j++) { //读取该行的第j列数据 string value = row.GetCell(j).ToString(); Console.Write(value.ToString() + " "); } Console.WriteLine("\n"); } } } catch (Exception e) { //只在Debug模式下才输出 Console.WriteLine(e.Message); } Console.WriteLine("Hello World!"); } } }