webapi将list转为datatable
/// <summary>
/// 将list转为datatable
/// </summary>
/// <typeparam name="ExcelExportModel"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ListToDataTable<ExcelExportModel>(List<ExcelExportModel> list)
{
//创建一个名为"tableName"的空表
DataTable dt = new DataTable();
//创建传入对象名称的列
foreach (var item in list.FirstOrDefault().GetType().GetProperties())
{
dt.Columns.Add(item.Name);
}
//循环存储
foreach (var item in list)
{
//新加行
DataRow value = dt.NewRow();
//根据DataTable中的值,进行对应的赋值
foreach (DataColumn dtColumn in dt.Columns)
{
int i = dt.Columns.IndexOf(dtColumn);
//基元元素,直接复制,对象类型等,进行序列化
//if (value.GetType().IsPrimitive)
//{
// value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
//}
//else
//{
// value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));//string类型则会有引号
//}
value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
}
dt.Rows.Add(value);
}
return dt;
}