将Datatable转换成实体List集合的方法

今天要做Execel文件导入项目里,要用到这个东西,所以就修修改改的写了一个方法,这个方法里实体用泛型表示。但是感觉这样写好像太复杂了,目前没有想到更好的可以提高效率的解决方案,如果有前辈看到了,帮我提点建议哦。

 /// <summary>
        /// 将datatable转换为实体集合 by  jelena 2013-05-13       
/// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static IList<T> DtExchangeEntList<T>(DataTable table) where T : new() { //初始化返回的实体列表 IList<T> list = new List<T>(); if (table != null) { //循环DataTable的行 for (int j = 1; j < table.Rows.Count; j++) { //导入标志为空不导入 if (table.Rows[j]["ImportFlag"] == null || table.Rows[j]["ImportFlag"].ToString().Trim() != "1") { continue; } StringBuilder ResultStr = new StringBuilder(); //创建对象实例 T ent = new T(); //根据DataTable 属性填充实体属性; PropertyInfo[] Properies = ent.GetType().GetProperties();//获取对象的所有属性 for (int i = 0; i < table.Columns.Count; i++) { foreach (PropertyInfo pinfo in Properies) { if (table.Columns[i].ColumnName.ToLower().Equals(pinfo.Name.ToLower())) { if (table.Rows[j][i] != DBNull.Value && table.Rows[j][i].ToString().Trim() != "") { if (pinfo.PropertyType == typeof(string)) { try { pinfo.SetValue(ent, table.Rows[j][i].ToString().Trim(), null); } catch { pinfo.SetValue(ent, "", null); ResultStr.Append("列‘" + table.Rows[0][i] + "’数据有误;"); } } else if (pinfo.PropertyType == typeof(int)) { try { double temp = double.Parse(table.Rows[j][i].ToString().Trim()); pinfo.SetValue(ent, Convert.ToInt32(temp.ToString()), null); } catch { pinfo.SetValue(ent, 0, null); ResultStr.Append("列‘" + table.Rows[0][i] + "’数据有误;"); } } else if (pinfo.PropertyType == typeof(long)) { try { pinfo.SetValue(ent, long.Parse(table.Rows[j][i].ToString().Trim()), null); } catch { pinfo.SetValue(ent, 0, null); ResultStr.Append("列‘" + table.Rows[0][i] + "’数据有误;"); } } else if (pinfo.PropertyType == typeof(DateTime)) { try { pinfo.SetValue(ent, DateTime.Parse(table.Rows[j][i].ToString().Trim()), null); } catch { pinfo.SetValue(ent, SysConstants.SYS_DEFAULTDATE, null); ResultStr.Append("列‘" + table.Rows[0][i] + "’数据有误;"); } } else if (pinfo.PropertyType == typeof(float)) { try { pinfo.SetValue(ent, float.Parse(table.Rows[j][i].ToString().Trim()), null); } catch { pinfo.SetValue(ent, 0.0, null); ResultStr.Append("列‘" + table.Rows[0][i] + "’数据有误;"); } } else if (pinfo.PropertyType == typeof(double)) { try { pinfo.SetValue(ent, double.Parse(table.Rows[j][i].ToString().Trim()), null); } catch { pinfo.SetValue(ent, 0.0, null); ResultStr.Append("列‘" + table.Rows[0][i] + "’数据有误;"); } } else if (pinfo.PropertyType == typeof(bool)) { try { string MS = table.Rows[j][i].ToString().Trim(); if (MS == "" || MS == "0") { pinfo.SetValue(ent, false, null); } else if (MS == "" || MS == "1") { pinfo.SetValue(ent, true, null); } } catch { pinfo.SetValue(ent, false, null); ResultStr.Append("列‘" + table.Rows[0][i] + "’数据有误;"); } } } break; } } } list.Add(ent); } } return list; }

 

posted @ 2013-05-14 18:43  豪迈人生  阅读(550)  评论(11编辑  收藏  举报