From 4374db5eb30856c1ece33a776a3afbabf049256c Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Singh Date: Tue, 15 Jun 2021 16:49:01 +0200 Subject: [PATCH] Update Worksheet.cs Worksheet does not have any functionality for converting rows back to object. You can read data from excel sheet this will return only rows with cell but not enumerable. This method will convert from rows to enumerable --- FastExcel/Worksheet.cs | 45 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) 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 +}