1. 程式人生 > >反射賦值

反射賦值

目前例子為NPOI Excel匯入 入庫時呼叫

 var file = file1.PostedFile.InputStream;
            var fileExt = System.IO.Path.GetExtension(file1.FileName);
            IWorkbook workbook;
            if (fileExt == ".xlsx")
                workbook = new XSSFWorkbook(file);
            else
                workbook 
= new HSSFWorkbook(file); DB.DBContext db = new DB.DBContext(); List<DB.Entity.dt_orders> list_orders = new List<DB.Entity.dt_orders>(); #region 訂單記錄 var sheet_order = workbook.GetSheet("訂單記錄"); if (sheet_order != null) { List
<string> list_hread = new List<string>(); //獲取Excel的最大行數 int rowsCount = sheet_order.PhysicalNumberOfRows; int colsCount = sheet_order.GetRow(1).PhysicalNumberOfCells; //獲取欄位 for (int i = 0; i < colsCount; i++) { list_hread.Add(sheet_order.GetRow(
1).GetCell(i).ToString()); } //資料填充 for (int x = 2; x < rowsCount; x++) { var model_order = new DB.Entity.dt_orders(); var row = sheet_order.GetRow(x); SetValue(model_order, row, list_hread); list_orders.Add(model_order); } //過濾掉已有的訂單 var list_ordersno = list_orders.Select(d => d.order_no).ToList(); var dt_list_ordersno = db.dt_orders.Where(d => list_ordersno.Contains(d.order_no)).Select(d => d.order_no).ToList(); list_orders.RemoveAll(d => dt_list_ordersno.Contains(d.order_no)); } #endregion

 

/// <summary>
        /// 反射賦值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="row"></param>
        /// <param name="list_hread"></param>
        private void SetValue<T>(T model, IRow row, List<string> list_hread)
        {
            System.Reflection.PropertyInfo[] myPropertyInfo = model.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < list_hread.Count; i++)
            {
                var hread = list_hread[i];
                var pi = model.GetType().GetProperty(hread);               
                try
                {
                    var value = Convert.ChangeType((object)row.GetCell(i).ToString(), (Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType));
                    pi.SetValue(model, value, null);
                }
                catch (Exception ex)
                {
                    pi.SetValue(model, null, null);
                }

            }
        }