hmfl

导航

 
    private static List<T> ReadExcelPackage<T>(T t, ExcelPackage package, ExcelWorksheet worksheet, int StartRow = 1) where T : new()
    {
        var rowCount = worksheet.Dimension?.Rows;
        var colCount = worksheet.Dimension?.Columns;

        if (!rowCount.HasValue || !colCount.HasValue)
        {
            return null;
        }

        var properties = t.GetType().GetProperties();
        var lists = new List<T>();

        for (int row = StartRow; row <= rowCount.Value; row++)
        {
            var model = new T();
            for (int col = 0; col < properties.Length; col++)
            {
                var value = worksheet.Cells[row, col + 1].Value;
                properties[col].SetValue(model, value?.ToString());
            }
            lists.Add(model);
        }

        return lists;
    }

为了图省事,T类型的类字段只能定义为string类型的,
如果定义为int类型时等,会出现异常转换错误,使用时要注意。
,properties[col].SetValue(model, value?.ToString());

posted on 2021-10-27 15:56  hmflhmfl  阅读(199)  评论(0编辑  收藏  举报