我有一個JSON
對象,我從ajax後調用中獲得,我將它映射到我的下面的Customclass對象列表中。無法將列表對象轉換爲數據表
[ObjectFilter(Param = "postdata", RootType = typeof(List<ExportToExcel8020>))]
public void ExportToExcel(List<ExportToExcel8020> text)
{
//List<ExportToExcel8020> rm = text.AsEnumerable().ToList();
//DataTable UserDt = rm .ToDataTable();
DataTable UserDt = text.ToDataTable();
}
這是我的名單物體的外觀,
現在我想這個generic list object
轉換成datatable
, 我試圖通過使用下面的方法來做到這一點。但我得到它說
「System.Collections.Generic.List < ... Domain.Common.ExportToExcel8020>」不包含「ToDataTable」,沒有擴展方法的定義「ToDataTable」接受的錯誤類型的第一個參數...
「System.Collections.Generic.List < ... Domain.Common.ExportToExcel8020>」找不到(是否缺少using指令或程序集引用?)
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
我需要它作爲datatable
的原因是使用openxml
並導出excel
文件。
我的代碼有問題嗎?或者是我的apporach本身是錯誤的?
看起來您正在嘗試創建擴展方法。你需要做'公共靜態數據表ToDataTable(這個列表項目)'。 –