A few months ago I posted
a article about exporting and formatting a datagridview to Excel.
Well what about exporting a
List<T>
to Excel?
Sure, some may wonder but what's the point? Cause it's very easy to have
like a hidden dataGridView and when exporting one could easily add something like
dvg1.DataSource = myList;
. While it is totally true, it does have a downside in the memory consumption. Sure for small amounts of data no problem but for like 50.000 items each containg like 10-15 properties(e.g. 50.000 rows by 10-15 columns) the extra memory is not so ignorable. In winforms the dgv keeps a copy of the actual datas => twice needed memory. Firts for the List and again
for the dgv.
Ok so I'm too lazy to update the article so I decided to post a tip/trick.
OK so for a cell by cell aproach(
SLOOOW) it will be something like:
int col=1;
foreach(var propInfo in lst[0].GetType().GetProperties())
{
excelSheet.Cells[1, col] = propInfo.Name;
col++;
}
for (int i = 0; i < lst.Count; i++)
{
int j = 1;
foreach (var propInfo in lst[i].GetType().GetProperties())
{
excelSheet.Cells[i+2, j].Value = propInfo.GetValue(lst[i], null);
j++;
}
}
Here is the code from the article that does a fast export.
It creates a two dimensional object[,] from the datagridview.
Ideea "stolen" from Peter Moon.
private object[,] CreateTwoDimensionalObject()
{
object[,] datas = new object[dgv.Rows.Count + 1, dgv.Rows[0].Cells.Count];
for (int col = 0; col < dgv.Columns.Count; col++)
{
datas[0, col] = dgv.Columns[col].HeaderText;
}
for (int col = 0; col < dgv.Rows[0].Cells.Count; col++)
{
for (int row = 0; row < dgv.Rows.Count; row++)
{
datas[row + 1, col] = dgv.Rows[row].Cells[col].Value.ToString();
}
}
return datas;
}
And Here is the method ported for a
List<T>
. List<object> actually:
private object[,] CreateTwoDimensionalObject()
{
object[,] datas= new object[lst.Count + 1, lst[0].GetProperTies.Count]
int col=0;
foreach(var propInfo in lst[0].GetType().GetProperties())
{
datas[0, col] = propInfo.Name;
col++;
}
for(int row=0; row<lst.Count; row++){
int column = 0;
foreach (var propInfo in lst[row].GetType().GetProperties()){
datas[row+1, column] = propInfo.GetValue(lst[row], null);
column++;
}
}
Supose the method is named Export.
Now, to export a List<MyType> heres the needed code/trick:
List<object> lst = new List<object>
for(int i=0; i<5000; i++){
MyType c = new MyType();
c.Val = i;
lst.Add(c);
}
Now export it:
My.... .Export(lst);
Ahh... the VARIANCE...
CO and
CONTRA off course.