【问题标题】:Help converting generic List<T> to Excel spreadsheet帮助将通用 List<T> 转换为 Excel 电子表格
【发布时间】:2010-12-22 07:23:50
【问题描述】:

我正在尝试创建一个函数,该函数接受通用 List&lt;T&gt; 并迭代返回 Excel 文件 byte[] 的列表。该函数需要能够确定对象的属性。因此,如果我通过List&lt;person&gt; 并且人员具有属性 first、last、age 等,我需要能够确定属性名称以创建 excel 列标题,然后我需要迭代列表以分配属性值到列单元格。谁能指出一些在通用函数中使用List&lt;T&gt; 的示例代码?

【问题讨论】:

    标签: c# excel generic-list


    【解决方案1】:

    除此之外:以已知顺序获取列:除了您创建的之外,没有为成员定义的顺序。例如(from MSDN):

    GetProperties 方法不按特定顺序返回属性,例如字母顺序或声明顺序。您的代码不得依赖于返回属性的顺序,因为该顺序会有所不同。

    如果您不需要依赖顺序,反射或 TypeDescriptor 都可以;例如(注意这写的是 TSV 文本,而不是 byte[] - 我的解释是问题在于获取数据,而不是写 Excel):

    static void WriteTsv<T>(this IEnumerable<T> data, TextWriter output)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        foreach (PropertyDescriptor prop in props)
        {
            output.Write(prop.DisplayName); // header
            output.Write("\t");
        }
        output.WriteLine();
        foreach (T item in data)
        {
            foreach (PropertyDescriptor prop in props)
            {
                output.Write(prop.Converter.ConvertToString(
                     prop.GetValue(item)));
                output.Write("\t");
            }
            output.WriteLine();
        }
    }
    

    如果您需要订购,您需要:

    • 传入(例如,params string[] propertyNames
    • 在属性上使用属性
    • 按字母顺序排列

    上述TypeDescriptor 方法具有以下优点(优于GetType().GetProperties()):

    • 它适用于自定义对象模型(例如DataView,如果您使用IList
    • 您可以调整实现以提高性能 - 例如 HyperDescriptor(如果您经常这样做,这很有用)

    【讨论】:

    • 我认为 Kevin 所说的“...属性名称以便创建...”是“...属性名称以便我可以创建...”,而不是排序列表属性名称:)
    • 天啊!我感觉很慢......我会保持“原样”,因为我认为如果您每次都期望相同的结果,这仍然是一个有趣的点。谢谢。
    • 谢谢 Marc,这就是我要找的。​​span>
    【解决方案2】:

    使用您的收藏支持的接口,例如IEnumerable

    public byte[] Process(IEnumerable input) {
        foreach (var elem in input) {
            foreach (PropertyInfo prop in elem.GetType().GetProperties()) {
                Object value = prop.GetValue(elem, null);
                // add value to byte[]
            }
        }
        return bytes;
    }
    

    【讨论】:

      【解决方案3】:

      最简单的方法可能是convert your List to a DataTable,然后是convert the DataTable to an Excel spreadsheet

      第二个链接将电子表格直接写入 ASP.NET 响应,这可以很容易地调整为返回一个字节[]。

      【讨论】:

        猜你喜欢
        • 2021-05-27
        • 2020-07-19
        • 1970-01-01
        • 2017-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-04
        • 2011-07-21
        相关资源
        最近更新 更多