using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using HuizhongLibrary.Data; using HuizhongLibrary.Log; namespace HuizhongLibrary { /// /// DataTable扩展 /// public static class DataTableExtension { #region DataTable转List /// /// DataTable转List /// /// 扩展对象 public static List ToList(this DataTable tb) { if (tb == null || tb.Rows.Count == 0) return null; //获取对象所有属性 Type t = typeof(T); List ListModel = new List(); PropertyInfo[] propertyInfo = t.GetProperties(); bool bk = false; string json = ""; if (propertyInfo.Length > 0) { #region 全部是属性 for (int i = 0; i < tb.Rows.Count; i++) { //创建泛型对象 DataRow row = tb.Rows[i]; T model = Activator.CreateInstance(); for (int j = 0; j < tb.Columns.Count; j++) { foreach (PropertyInfo info in propertyInfo) { //属性名称和列名相同时赋值 if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper())) { bk = SetPropertyValue(model, info, row[j]); if (bk == false) { json = row.ToJson(); ErrorFollow.TraceWrite("转换错误", "行信息", json); break; } } } } ListModel.Add(model); } #endregion } else { #region 全部是字段 FieldInfo[] fieldinfo = t.GetFields(); for (int i = 0; i < tb.Rows.Count; i++) { //创建泛型对象 DataRow row = tb.Rows[i]; T model = Activator.CreateInstance(); for (int j = 0; j < tb.Columns.Count; j++) { foreach (FieldInfo info in fieldinfo) { //属性名称和列名相同时赋值 if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper())) { bk = SetFieldValue(model, info, row[j]); if (bk == false) { json = row.ToJson(); ErrorFollow.TraceWrite("转换错误", "行信息", json); break; } } } } ListModel.Add(model); } #endregion } return ListModel; } #endregion #region 转换DataRow为Model public static T ToModel(this DataRow row) { //获取对象所有属性 DataTable tb = row.Table; Type t = typeof(T); T model = Activator.CreateInstance(); PropertyInfo[] propertyInfo = t.GetProperties(); bool bk = false; string json = ""; if (propertyInfo.Length > 0) { for (int j = 0; j < tb.Columns.Count; j++) { foreach (PropertyInfo info in propertyInfo) { //属性名称和列名相同时赋值 if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper())) { bk=SetPropertyValue(model, info, row[j]); if (bk == false) { json = row.ToJson(); ErrorFollow.TraceWrite("转换错误", "行信息", json); break; } } } } } else { FieldInfo[] fieldinfo = t.GetFields(); for (int j = 0; j < tb.Columns.Count; j++) { foreach (FieldInfo info in fieldinfo) { //属性名称和列名相同时赋值 if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper())) { bk=SetFieldValue(model, info, row[j]); if (bk == false) { json = row.ToJson(); ErrorFollow.TraceWrite("转换错误", "行信息", json); break; } } } } } return model; } #endregion #region 属性赋值 public static bool SetPropertyValue(T model,PropertyInfo info,object value) { if (value == DBNull.Value || value == null) { info.SetValue(model, null, null); return true; } if (info.PropertyType == typeof(byte[])) { info.SetValue(model, (byte[])value, null); return true; } string val = Convert.ToString(value); if (val == "") { if (info.PropertyType == typeof(string)) { info.SetValue(model, Convert.ToString(val), null); } else { info.SetValue(model, null, null); } return true; } try { if (info.PropertyType == typeof(byte) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToByte(val), null); } else if (info.PropertyType == typeof(Int16) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToInt16(val), null); } else if (info.PropertyType == typeof(int) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToInt32(val), null); } else if (info.PropertyType == typeof(Int64) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToInt64(val), null); } else if (info.PropertyType == typeof(bool) || info.PropertyType == typeof(Nullable)) { if (val == "True" || val == "False") { info.SetValue(model, Convert.ToBoolean(val), null); } else { int valbool = Convert.ToInt32(val); info.SetValue(model, Convert.ToBoolean(valbool), null); } } else if (info.PropertyType == typeof(decimal) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToDecimal(val), null); } else if (info.PropertyType == typeof(Double) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToDouble(val), null); } else if (info.PropertyType == typeof(Single) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToSingle(val), null); } else if (info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(Nullable)) { info.SetValue(model, Convert.ToDateTime(val), null); } else { info.SetValue(model, Convert.ToString(val), null); } return true; } catch (Exception ex) { string str = "列名="+ info.Name+",内容="+ val; ErrorFollow.TraceWrite("数据格式转换错误", "", str); ErrorFollow.TraceWrite(ex.TargetSite.Name,ex.StackTrace, ex.Message); } return false; } #endregion #region 字段赋值 public static bool SetFieldValue(T model, FieldInfo info, object value) { if (value == DBNull.Value || value == null) { info.SetValue(model, null); return true; } if (info.FieldType == typeof(byte[])) { info.SetValue(model, (byte[])value); return true; } string val = Convert.ToString(value); if (val == "") { if (info.FieldType == typeof(string)) { info.SetValue(model, Convert.ToString(val)); } else { info.SetValue(model, null); } return true; } try { if (info.FieldType == typeof(byte) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToByte(val)); } else if (info.FieldType == typeof(Int16) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToInt16(val)); } else if (info.FieldType == typeof(int) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToInt32(val)); } else if (info.FieldType == typeof(Int64) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToInt64(val)); } else if (info.FieldType == typeof(bool) || info.FieldType == typeof(Nullable)) { if (val == "True" || val == "False") { info.SetValue(model, Convert.ToBoolean(val)); } else { int valbool = Convert.ToInt32(val); info.SetValue(model, Convert.ToBoolean(valbool)); } } else if (info.FieldType == typeof(decimal) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToDecimal(val)); } else if (info.FieldType == typeof(Double) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToDouble(val)); } else if (info.FieldType == typeof(Single) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToSingle(val)); } else if (info.FieldType == typeof(DateTime) || info.FieldType == typeof(Nullable)) { info.SetValue(model, Convert.ToDateTime(val)); } else { info.SetValue(model, Convert.ToString(val)); } return true; } catch (Exception ex) { string str = "列名=" + info.Name + ",内容=" + val; ErrorFollow.TraceWrite("数据格式转换错误", "", str); ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); } return false; } #endregion #region DataTable转Json public static string ToJson(this DataTable tb) { if (tb.Rows.Count == 0) return ""; DateTime time = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc); long DatetimeMinTimeTicks = time.Ticks; string s = "["; foreach (DataRow row in tb.Rows) { string a = "{"; foreach (DataColumn col in tb.Columns) { if (col.ExtendedProperties.Contains("NoJson") == true) continue; if (row.IsNull(col.ColumnName) == true) { a += "\"" + col.ColumnName + "\":null,"; continue; } if (col.DataType == typeof(string) || col.DataType == typeof(System.Guid)) { string vvv = row[col.ColumnName].ToString(); vvv = vvv.Replace("\r\n", "\\r\\n").Replace("\n", "\\n"); a += "\"" + col.ColumnName + "\":\"" + vvv + "\","; continue; } if (col.DataType == typeof(DateTime)) { DateTime datetime = Convert.ToDateTime(row[col.ColumnName]); a += "\"" + col.ColumnName + "\":\"\\/Date(" + (long)((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710) + ")\\/\","; continue; } if (col.DataType == typeof(bool)) { a += "\"" + col.ColumnName + "\":" + row[col.ColumnName].ToString().ToLower() + ","; continue; } if (col.DataType == typeof(Int64)) { a += "\"" + col.ColumnName + "\":\"" + row[col.ColumnName] + "\","; continue; } if (col.DataType == typeof(decimal)) { a += "\"" + col.ColumnName + "\":" + Convert.ToDecimal(row[col.ColumnName]).ToString("0.#########") + ","; continue; } if (col.DataType == typeof(Int32) || col.DataType == typeof(Int16) || col.DataType == typeof(float) || col.DataType == typeof(short)) { a += "\"" + col.ColumnName + "\":" + row[col.ColumnName] + ","; continue; } } a = a.Remove(a.Length - 1); a += "},"; s += a; } s = s.Remove(s.Length - 1); s += "]"; return s; } #endregion #region 转换DataRow为Json public static string ToJson(this DataRow row) { DateTime time = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc); long DatetimeMinTimeTicks = time.Ticks; string a = "{"; foreach (DataColumn col in row.Table.Columns) { if (col.ExtendedProperties.Contains("NoJson") == true) continue; if (row.IsNull(col.ColumnName) == true) { a += "\"" + col.ColumnName + "\":null,"; continue; } if (col.DataType == typeof(string) || col.DataType == typeof(System.Guid)) { string vvv = row[col.ColumnName].ToString(); vvv = vvv.Replace("\r\n", "\\r\\n").Replace("\n", "\\n"); a += "\"" + col.ColumnName + "\":\"" + vvv + "\","; continue; } if (col.DataType == typeof(DateTime)) { DateTime datetime = Convert.ToDateTime(row[col.ColumnName]); a += "\"" + col.ColumnName + "\":\"\\/Date(" + (long)((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710) + ")\\/\","; continue; } if (col.DataType == typeof(bool)) { a += "\"" + col.ColumnName + "\":" + row[col.ColumnName].ToString().ToLower() + ","; continue; } if (col.DataType == typeof(Int64)) { a += "\"" + col.ColumnName + "\":\"" + row[col.ColumnName] + "\","; continue; } if (col.DataType == typeof(decimal)) { a += "\"" + col.ColumnName + "\":" + Convert.ToDecimal(row[col.ColumnName]).ToString("0.#########") + ","; continue; } if (col.DataType == typeof(Int32) || col.DataType == typeof(Int16) || col.DataType == typeof(float) || col.DataType == typeof(short)) { a += "\"" + col.ColumnName + "\":" + row[col.ColumnName] + ","; continue; } } a = a.Remove(a.Length - 1); a += "}"; return a; } #endregion #region DataTable转JavaDataTable public static JavaDataTable ToJavaDataTable(this DataTable tb) { var tb2 = new JavaDataTable(); foreach (DataColumn item in tb.Columns) { tb2.Columns.Add(new JavaDataTableColumn { ColumnName = item.ColumnName }); } foreach (DataRow item in tb.Rows) { var row = new JavaDataTableRow(); row.ItemArray = item.ItemArray.ToList(); tb2.Rows.Add(row); } return tb2; } #endregion } }