C# 将sheet中数据转为list

   
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; }

调用如下:

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(); 
}
            

 说明:以上代码可以实现从Excel中读取数据,并将每个sheet里的对象集合放在一个list中。对于一个Excel,多次调用以上方法即可。

这些代码只是初步取出了数据,并没有进行数据为空等的校验,需要根据业务需要进行修改。

转载于:https://www.cnblogs.com/tomspapaya/p/3643682.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值