今天要做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; }