diff --git a/FastExcel/Worksheet.cs b/FastExcel/Worksheet.cs index 38b9a5b..426d018 100644 --- a/FastExcel/Worksheet.cs +++ b/FastExcel/Worksheet.cs @@ -219,6 +219,49 @@ private void PopulateRowsFromIEnumerable(IEnumerable> rows, Rows = newRows; } + + /// + /// Convert Rows back to Object + /// + /// + /// + /// + public List MapToObject(IEnumerable rows, int existingHeadingRows = 0) + { + int rowNumber = existingHeadingRows + 1; + + var collectionType = typeof(List<>).MakeGenericType(typeof(T)); + var list = Activator.CreateInstance(collectionType); + + var addMethod = collectionType.GetMethod("Add"); + + // Get all property for map + IEnumerable properties = typeof(T).GetRuntimeProperties(); + foreach (Row row in rows.Skip(existingHeadingRows)) + { + int propertyIndex = 1; + var objectInstance = Activator.CreateInstance(typeof(T)); + foreach (PropertyInfo propertyInfo in properties) + { + var colName = Cell.GetExcelColumnName(propertyIndex); + if (row.Cells.Where(x => x.ColumnName == colName && x.RowNumber == rowNumber).Any()) + { + var value = row.Cells.Where(x => x.ColumnName == colName && x.RowNumber == rowNumber).SingleOrDefault().Value; + if (propertyInfo.PropertyType == typeof(DateTime)) + { + double dateValue; + if (double.TryParse(value.ToString(), out dateValue)) + value = DateTime.FromOADate(dateValue); + } + propertyInfo.SetValue(objectInstance, Convert.ChangeType(value,propertyInfo.PropertyType)); + } + propertyIndex++; + } + rowNumber++; + addMethod.Invoke(list, new object[] { objectInstance }); + } + return (List)list; + } /// /// Add a row using a collection of value objects @@ -706,4 +749,4 @@ internal WorksheetAddSettings AddSettings } } } -} \ No newline at end of file +}