一个Excel导出类的实现过程(一):泛型与反射

对数据进行导出要求很常见,我们需要通用便离不了泛型和反射。这里从伪码开始,逐步加入业务需求、场景及边界,最终使用NPOI组件实现。

准备好业务中的实体类准备好:

public class Person
{
    public Int32 ID { get; set; }
    public String Name { get; set; }
    public DateTime Birth { get; set; }
    public Double Salary { get; set; }
}

接着是函数原型:

Export<T>(IList<T> records)

接下来我们开始干活。首先是PropertyInfo数组可以通过Type.GetProperties()及其各种重载方法实现,然后是PropertyInfo.GetValue()方法可以从类的实例中获取值,第一个原型如下:

static void Main(string[] args)
{
    List<Person> persons = new List<Person>();
    persons.Add(new Person { ID = 1, Name = "Rattz", Birth = new DateTime(1980, 10, 1), Salary = 20.2D });
    persons.Add(new Person { ID = 2, Name = "Mike", Birth = new DateTime(1988, 2, 15), Salary = 20.2D });

    Export<Person>(persons);
}

static void Export<T>(IList<T> records)
{
    if (records == null)
        throw new ArgumentNullException("records");

    PropertyInfo[] props = typeof(T).GetProperties(); //获取属性
    for (Int32 i = 0; i < props.Length; i++)
    {
        Console.Write(props[i].Name);
        Console.Write("\t");
    }
    Console.WriteLine();

    foreach (var record in records)
    {
        for (Int32 i = 0; i < props.Length; i++)
        {
            Object value = props[i].GetValue(record, null); //获取值
            Console.Write(value);
            Console.Write("\t");
        }
        Console.WriteLine();
    }
}

这里只是缩进与打印,我们可以处理很多其他事情;同时这里records只有两条,实际业务中超过65536条记录的导出要求也会出现,在介绍与使用NPOI的过程中我们一并处理。

posted @ 2013-05-16 16:29  Jusfr  阅读(754)  评论(0编辑  收藏  举报