我是一名 ASP.NET 程式員,專註於 B/S 項目開發。累計文章閱讀量超過一千萬,我的博客主頁地址:https://www.itsvse.com/blog_xzz.html 網上有很多關於npoi讀取excel表格的例子,很多都是返回一個Datatable的對象,但是我需要的是一個list集合, ...
我是一名 ASP.NET 程式員,專註於 B/S 項目開發。累計文章閱讀量超過一千萬,我的博客主頁地址:https://www.itsvse.com/blog_xzz.html
網上有很多關於npoi讀取excel表格的例子,很多都是返回一個Datatable的對象,但是我需要的是一個list集合,這裡就需要把Datatable轉成自己需要的List集合,所以,我封裝了一個方法,傳入class對象就能返回相應的list對象。
首先先看效果圖,如下:
模板
一共有4列,有很多行,其中只有2行有數據,如下圖:
特性
首先,定義一個特性,意義是對象的屬性對應表格的哪一列,代碼如下:
public class ColumnAttribute: Attribute { public ColumnAttribute(int index) { Index = index; } public int Index { get; set; } }
對象模型
將表格數據讀取出來,轉換成相應的對象集合,在對象的屬性標註上面定義的特性,代碼如下:
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
代碼如下:
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; } }
調用代碼:
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(); }
最後,就出現了文章最開始的效果圖。
轉載於:https://down.itsvse.com/k/0tmhog.html