我是一名 ASP.NET 程序員,專一於 B/S 項目開發。累計文章閱讀量超過一千萬,個人博客主頁地址:https://www.itsvse.com/blog_xzz.htmlhtml
網上有不少關於npoi讀取excel表格的例子,不少都是返回一個Datatable的對象,可是我須要的是一個list集合,這裏就須要把Datatable轉成本身須要的List集合,因此,我封裝了一個方法,傳入class對象就能返回相應的list對象。程序員
首先先看效果圖,以下:json
一共有4列,有不少行,其中只有2行有數據,以下圖:excel
首先,定義一個特性,意義是對象的屬性對應表格的哪一列,代碼以下:orm
public class ColumnAttribute: Attribute { public ColumnAttribute(int index) { Index = index; } public int Index { get; set; } }
將表格數據讀取出來,轉換成相應的對象集合,在對象的屬性標註上面定義的特性,代碼以下:htm
public class TestModel { [Column(0)] public string Name { get; set; } [Column(1)] public string Url { get; set; } [Column(2)] public string Date { get; set; } [Column(3)] public string Remark { get; set; } }
nuget安裝npoi:對象
Install-Package DotNetCore.NPOI -Version 1.2.2
代碼以下:blog
public class ExcelHelper { /// <summary> /// 讀取excel轉換成list集合 /// </summary> /// <typeparam name="T">對象</typeparam> /// <param name="stream">文件流</param> /// <param name="startIndex">從第幾行開始讀取</param> /// <param name="sheetIndex">讀取第幾個sheet</param> /// <returns></returns> public static IList<T> GetList<T>(Stream stream, int startIndex, int sheetIndex = 0) where T : class { IList<T> ts = new List<T>(); try { IWorkbook workbook = WorkbookFactory.Create(stream); var sheet = workbook.GetSheetAt(sheetIndex); if (sheet != null) { IRow firstRow = sheet.GetRow(0); //一行最後一個cell的編號 即總的列數 int cellCount = firstRow.LastCellNum; //最後一列的標號 int rowCount = sheet.LastRowNum; for (int i = startIndex; i <= rowCount; ++i) { //獲取行的數據 IRow row = sheet.GetRow(i); if (row == null) continue; //沒有數據的行默認是null { T model = Activator.CreateInstance<T>(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) { var rowTemp = row.GetCell(j); string value = null; if (rowTemp.CellType == CellType.Numeric) { short format = rowTemp.CellStyle.DataFormat; if (format == 14 || format == 31 || format == 57 || format == 58 || format == 20) value = rowTemp.DateCellValue.ToString("yyyy-MM-dd"); else value = rowTemp.NumericCellValue.ToString(); } else value = rowTemp.ToString(); //賦值 foreach (System.Reflection.PropertyInfo item in typeof(T).GetProperties()) { var column = item.GetCustomAttributes(true).First(x => x is ColumnAttribute) as ColumnAttribute; if (column.Index == j) { item.SetValue(model, value); break; } } } } ts.Add(model); } } } } catch (Exception) { throw; } finally { if (stream != null) stream.Close(); } return ts; } }
調用代碼:ip
static void Main(string[] args) { FileStream fs = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/test.xlsx", FileMode.Open, FileAccess.Read); var temp = ExcelHelper.GetList<TestModel>(fs, 3); var json1 = Newtonsoft.Json.JsonConvert.SerializeObject(temp.Where(x => !string.IsNullOrWhiteSpace(x.Name)).ToList()); Console.WriteLine(json1); Console.WriteLine("ok"); Console.ReadKey(); }
最後,就出現了文章最開始的效果圖。開發