export IEnumerable<T> to Excel

Omu picture Omu · Jul 26, 2010 · Viewed 9.9k times · Source

anybody knows how or some library to use for this ?

Answer

Rob picture Rob · Jul 26, 2010

The code below is code I use to convert an IEnumerable<T> to a DataTable containing columns named for each property, along with the values of each item in the IEnumerable as rows. It's a very small hop from this to saving it as a CSV file

public class IEnumerableToDataTable
{
    public  static DataTable CreateDataTableForPropertiesOfType<T>()
    {
        DataTable dt = new DataTable();
        PropertyInfo[] piT = typeof(T).GetProperties();

        foreach (PropertyInfo pi in piT)
        {
            Type propertyType = null;
            if (pi.PropertyType.IsGenericType)
            {
                propertyType = pi.PropertyType.GetGenericArguments()[0];
            }
            else
            {
                propertyType = pi.PropertyType;
            }
            DataColumn dc = new DataColumn(pi.Name, propertyType);

            if (pi.CanRead)
            {
                dt.Columns.Add(dc);
            }
        }

        return dt;
    }

    public static DataTable ToDataTable<T>(IEnumerable<T> items)
    {
        var table = CreateDataTableForPropertiesOfType<T>();
        PropertyInfo[] piT = typeof(T).GetProperties();

        foreach (var item in items)
        {
            var dr = table.NewRow();

            for (int property = 0; property < table.Columns.Count; property++)
            {
                if (piT[property].CanRead)
                {
                    dr[property] = piT[property].GetValue(item, null);
                }
            }

            table.Rows.Add(dr);
        }
        return table;
    }
}

So, you could write the following to convert your data to a datatable:

IEnumerable<Thing> values = GetMyIEnumerableValues();

var tableOfData = IEnumerableToDataTable.ToDataTable(values);

Once it's there, it's fairly trivial to write it out to a CSV file, or any other format of your choice, as all the "tricky" reflection work to extract the data from the IEnumerable<T> has been done.