由于使用NPOI生成Excel的时候,传入的数据类型是需要Datatable的,但是我获取到的数据是List类型,只有通过转换一下才可以传入
于是就有了:
List转Datatable的一个方法
需要引用一下

 using System.Reflection;
        public static DataTable List2Table(this List items)
        {
            DataTable dataTable = new DataTable();

            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                dataTable.Columns.Add(prop.Name, prop.PropertyType);
            }

            foreach (T obj in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    values[i] = Props[i].GetValue(obj, null);
                }
                dataTable.Rows.Add(values);
            }

            return dataTable;
        }

   

顺便带上反过来的Datatable转List

    
        public static List Table2List(this DataTable dt)
        {
            var dataColumn = dt.Columns.Cast().Select(c => c.ColumnName).ToList();

            var properties = typeof(T).GetProperties();
            string columnName = string.Empty;

            return dt.AsEnumerable().Select(row =>
            {
                var t = Activator.CreateInstance();
                foreach (var p in properties)
                {
                    columnName = p.Name;
                    if (dataColumn.Contains(columnName))
                    {
                        if (!p.CanWrite)
                            continue;

                        object value = row[columnName];
                        Type type = p.PropertyType;

                        if (value != DBNull.Value)
                        {
                            p.SetValue(t, Convert.ChangeType(value, type), null);
                        }
                    }
                }
                return t;
            }).ToList();
        }