首页 新闻 赞助 找找看

.net中如何把获得的List<T>数据转化为DataTable,用于导出excel用,求解?

0
悬赏园豆:20 [已解决问题] 解决于 2014-06-23 21:19

.net中如何把获得的List<T>数据转化为DataTabel,用于导出excel用,求解?反射的方式网上都这类方式,感觉不适用 ,求另外方法?

renshen4322的主页 renshen4322 | 初学一级 | 园豆:5
提问于:2014-06-15 21:15
< >
分享
最佳答案
0

你何必如此呢?如何将数据存到excel才是你关心的问题

收获园豆:20
迅捷网络[来送福利] | 小虾三级 |园豆:616 | 2014-06-16 08:40
其他回答(5)
0

什么叫感觉不适用```不反射你怎么知道T里面有多少字段,每个字段值又怎么取出来?就是反射了.别想别的

吴瑞祥 | 园豆:29449 (高人七级) | 2014-06-16 07:51
0

直接在list里面取数据是最合理的。

不过楼需要的话 我这里有段代码 

 public static class List2DataTable
    {
        #region "Convert Generic List to DataTable"
        /// <summary>
        /// Convert a List{T} to a DataTable.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public static DataTable ConvertToDataTable<T>(this List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                tb.Rows.Add(values);
            }
            return tb;
        }

        /// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type.
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
        #endregion
    }

调用

   xxx.ToList().ConvertToDataTable();

 

xxx是你的list<x>的变量

s_p | 园豆:138 (初学一级) | 2014-06-16 09:16
0

你直接吧list<T>导出excel不是很直接?效率还高,可控性还好

刘宏玺 | 园豆:14020 (专家六级) | 2014-06-16 12:15
0

是的,可以考虑直接把list<T>导出excel,在T:模型中定义你要导出的字段,这样效率也蛮高的,

小熊QQ糖 | 园豆:152 (初学一级) | 2014-06-16 17:35
0

你的数据源是 List<T>  这个T只是个占位符可以被任何类替换,只能通过反射 来取字段与属性并给 DataTable

Zery | 园豆:6151 (大侠五级) | 2014-06-17 23:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册