Export Model to DataTable

前端 未结 3 969
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    You can use ToDataTable extension method but you need to install MoreLinq first. To install MoreLINQ, run the following command in the Package Manager Console:

    PM> Install-Package morelinq

    Then add the following line to your using directives:

    using MoreLinq;
    

    And finally you can use ToDataTable extension method:

    DataTable s = db.EMPs.ToDataTable();
    
    0 讨论(0)
  • 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<EMP> 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);
    }
    
    0 讨论(0)
  • 2020-12-02 03:30

    To quickly create a file that can be read in Excel you could map the contents to a comma-separated value list using LINQ and then save the array to a file stream.

    var records = db.EMP
                    .ToList()
                    .Select(record => $"\"{record.stringField}\",{record.numberField}")
                    .ToArray();
    File.WriteAllLines("file.csv", records);
    
    0 讨论(0)
提交回复
热议问题