反射赋值
目前例子为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); } } }