using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace Ecolab_CST.Utils
{
/// <summary>
/// DataTable扩展方法类
/// </summary>
public static class DataTableExtend
{
/// <summary>
/// DataTable转成List
/// </summary>
public static List<T> ToDataList<T>(this DataTable dt)
{
var list = new List<T>();
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
foreach (DataRow row in dt.Rows)
{
T s = Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo prop = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (prop != null&& prop.CanWrite)
{
try
{
if (!Convert.IsDBNull(row[i]))
{
object v = null;
if (prop.PropertyType == typeof(bool)||Nullable.GetUnderlyingType(prop.PropertyType) == typeof(bool))
{
v = row[i].ToString() == "1" ? true : false;
}
else
{
// 泛型属性可空类型
if ((prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) || prop.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(row[i], Nullable.GetUnderlyingType(prop.PropertyType));
}
else
{
v = Convert.ChangeType(row[i], prop.PropertyType);
}
}
prop.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + prop.Name + "]转换出错," + ex.Message);
}
}
}
list.Add(s);
}
return list;
}
public static bool BoolParse(string str)
{
if (str == "0" || str == "")
{
return false;
}
else if (str == "1")
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// DataTable转成实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static T ToDataEntity<T>(this DataTable dt)
{
T s = Activator.CreateInstance<T>();
if (dt == null || dt.Rows.Count == 0)
{
return default(T);
}
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(dt.Rows[0][i]
NPOI 读取Excel 数据中 DataTable 和List互转
于 2022-03-11 17:00:21 首次发布