一个Excel导出类的实现过程(一):泛型与反射
生活随笔
收集整理的這篇文章主要介紹了
一个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的過程中我們一并處理。
轉載于:https://www.cnblogs.com/Jusfr/archive/2013/05/16/3082091.html
總結
以上是生活随笔為你收集整理的一个Excel导出类的实现过程(一):泛型与反射的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 不够优秀就不要腆着脸继续占便宜——作者:
- 下一篇: java读写html文件时出现中文乱码问