I want to convert my Model data to DataSet
or DataTable
(to export in excel format)
db.EMPs.ToList()
db
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();
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);
}
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);