在.NET Core 使用NPOI讀取Excel數據映射到List集合中

網上有很多關於npoi讀取excel表格的例子,很多都是返回一個Datatable的對象,但是我需要的是一個list集合,這裡就需要把Datatable轉成自己需要的List集合,所以,我封裝了一個方法,傳入class對象就能返回相應的list對象。

首先先看效果圖,如下:

在.NET Core 使用NPOI讀取Excel數據映射到List集合中

模板

一共有4列,有很多行,其中只有2行有數據,如下圖:

在.NET Core 使用NPOI讀取Excel數據映射到List集合中

特性

首先,定義一個特性,意義是對象的屬性對應表格的哪一列,代碼如下:

<code>public class ColumnAttribute: Attribute

    {

        public ColumnAttribute(int index)

        {

            Index = index;

        }

        public int Index { get; set; }

    }

  /<code>

對象模型

將表格數據讀取出來,轉換成相應的對象集合,在對象的屬性標註上面定義的特性,代碼如下:


<code>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; }

    }/<code>

  

封裝的方法

nuget安裝npoi:

<code>Install-Package DotNetCore.NPOI -Version 1.2.2/<code>

代碼如下:

<code>public class ExcelHelper

    {

        /// <summary>

        /// 讀取excel轉換成list集合

        /// /<summary>

        /// <typeparam>對象/<typeparam>

        /// <param>文件流

        /// <param>從第幾行開始讀取

        /// <param>讀取第幾個sheet

        /// <returns>

        public static IList GetList(Stream stream, int startIndex, int sheetIndex = 0)

            where T : class

        {

            IList ts = new List();

            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();

                            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;

        }

    }
/<code>

  

調用代碼:

<code>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();

        }/<testmodel>/<code>

  最後,就出現了文章最開始的效果圖。


分享到:


相關文章: