Created
August 19, 2019 21:45
-
-
Save jmbeach/e7169e0142fa5bd4ea15c9c0f4996694 to your computer and use it in GitHub Desktop.
Helpers for easily mapping objects to rows of an excel document in c# using EPPlus library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static ExcelRangeBase GetColumnByName(ExcelWorksheet sheet, string columnName) | |
{ | |
return sheet.Cells["1:1"].FirstOrDefault(x => x.Value.ToString() == columnName); | |
} | |
private static void MapColumns<TExportObject>(int row, ExcelWorksheet sheet, List<string> columnNames, List<Expression<Func<TExportObject, object>>> maps, TExportObject source) | |
{ | |
for (var i = 0; i < columnNames.Count; i++) | |
{ | |
var columnName = columnNames[i]; | |
var column = GetColumnByName(sheet, columnName); | |
if (column == null) | |
{ | |
_log.Log("Missing column " + columnName); | |
} | |
var propertyBody = maps[i].Body; | |
if (propertyBody is UnaryExpression && propertyBody.NodeType == ExpressionType.Convert) | |
{ | |
propertyBody = ((UnaryExpression)propertyBody).Operand; | |
} | |
var propertyInfo = propertyBody as MemberExpression; | |
if (propertyInfo != null) | |
{ | |
var property = propertyInfo.Member as PropertyInfo; | |
var val = property.GetValue(source); | |
if (val != null) | |
{ | |
sheet.Cells[row, column.Start.Column].Value = val; | |
} | |
} | |
else if (typeof(TExportObject) == typeof(string)) | |
{ | |
sheet.Cells[row, column.Start.Column].Value = source; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment