0
votes

I am trying to get rows value form excel but having only one record i had attached screen... check that below screen

Code:

 using System;
    using OfficeOpenXml;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;    
    
    namespace EpPlusExcelToObject
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Console.WriteLine("Test");
                string file = @"C:\Users\Applicantdetails.xlsx";
                using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(file))) 
                {
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    var sheet = package.Workbook.Worksheets["Applicantdata"];
                    var applicants = new Program().GetList<Applicant>(sheet);
                }
            }
            private List<T> GetList<T>(ExcelWorksheet sheet)
            {
                List<T> list = new List<T>();
                //first row is for knowing the properties of object
                var columnInfo = Enumerable.Range(1, sheet.Dimension.Columns).ToList().Select(n=>
                new {Index=n,ColumnName=sheet.Cells[1,n].Value.ToString()}
                );
                for(int row=2; row<sheet.Dimension.Rows;row++)
                {
                  T obj = (T)Activator.CreateInstance(typeof(T));//genric object
                    foreach(var prop in typeof(T).GetProperties())
                    {
                        int col = columnInfo.SingleOrDefault(c => c.ColumnName == prop.Name).Index;
                        var val = sheet.Cells[row, col].Value;
                        var propType = prop.PropertyType;
                        prop.SetValue(obj, Convert.ChangeType(val, propType));
                    }
                    list.Add(obj);
                }
                return list;
            }
        } 

//Applicant public class Applicant { public string Firstname { get; set; } public string Lastname { get; set; } public string Email { get; set; } } }

Kindly refer the screen Excel screen