首页 > 其他 > 详细

C# 将sheet中数据转为list

时间:2014-04-04 12:49:13      阅读:541      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
   
public IList<T> ExportToList<T>(ISheet sheet, string[] fields) where T : class,new() { IList<T> list = new List<T>(); //遍历每一行数据 for (int i = sheet.FirstRowNum + 1, len = sheet.LastRowNum + 1; i < len; i++) { T t = new T(); IRow row = sheet.GetRow(i); for (int j = 0, len2 = fields.Length; j < len2; j++) { Type propertyType = typeof(T).GetProperty(fields[j]).PropertyType; //获取当前属性的类型 ICell cell = row.GetCell(j); object cellValue = null; if (cell == null) { continue; } if(propertyType == typeof(string) | cell.CellType == CellType.Blank) { cell.SetCellType(CellType.String); cellValue = cell.StringCellValue; } if (propertyType == typeof(int) && cell.CellType != CellType.Blank) { cell.SetCellType(CellType.Numeric); cellValue = Convert.ToInt32(cell.NumericCellValue); //Double转int } if (propertyType == typeof(bool)) { cell.SetCellType(CellType.Boolean); cellValue = cell.BooleanCellValue; } typeof(T).GetProperty(fields[j]).SetValue(t, cellValue, null); } list.Add(t); } return list; }
bubuko.com,布布扣

调用如下:

bubuko.com,布布扣
static void Main(string[] args)
        {

            string _fromfile = @"D:\code\csharp\person.xlsx";
            string _tofile = @"D:\test.xlsx";
            
            IWorkbook book = null;
            try
            {
                book = new XSSFWorkbook(_fromfile);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                book = new HSSFWorkbook(File.OpenRead(_fromfile));
            }

            ISheet sheet = book.GetSheet("person");
            

            ExcelHelper helper = new ExcelHelper(_fromfile);
          
            string[] properties = new string[] { "name", "age", "sex", "id", "height", "weight", "country", "hometown", "phone" };
            foreach (var p in helper.ExportToList<Person>(sheet, properties))
            {
                Console.WriteLine("   " + p.name.GetType() + "   " + p.phone  + "  " + p.sex  + "   "  + p.weight.GetType());
            }
            Console.Read(); 
}
            
bubuko.com,布布扣

 

C# 将sheet中数据转为list,布布扣,bubuko.com

C# 将sheet中数据转为list

原文:http://www.cnblogs.com/tomspapaya/p/3643682.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!