将IEnumerable <T>导出到Excel

Omu*_*Omu 10 .net c# asp.net-mvc excel export-to-excel

有谁知道如何或一些图书馆用于此?

Rob*_*Rob 15

下面的代码是代码我使用一个转换IEnumerable<T>到含有命名为每个属性的列的DataTable,与每个项目在IEnumerable的值作为行沿.这是一个非常小的跳跃,将其保存为CSV文件

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以编写以下内容将数据转换为数据表:

IEnumerable<Thing> values = GetMyIEnumerableValues();

var tableOfData = IEnumerableToDataTable.ToDataTable(values);
Run Code Online (Sandbox Code Playgroud)

一旦它的存在,它相当琐碎写出来到CSV文件,或您选择的任何其他格式,从所有的"刁钻"的反思工作来提取数据IEnumerable<T>已经完成.