Export Model to DataTable

前端 未结 3 972
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 02:25

I want to convert my Model data to DataSet or DataTable (to export in excel format)

db.EMPs.ToList()

db

3条回答
  •  温柔的废话
    2020-12-02 03:26

    Using MoreLinq is the best way to convert a class to DataTable as already answered by S.Akbari Below is another way I found to accomplish this by using System.Reflection

    List list= db.EMPs.ToList();
    DataTable dt = new DataTable();       
    PropertyInfo[] Props = typeof(EMP).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo prop in Props)
    {
        //Setting column names as Property names
        dt.Columns.Add(prop.Name);
    }
    
    foreach (EMP e in list)
    {
        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(e, null);
        }
        dt.Rows.Add(values);
    }
    

提交回复
热议问题