Skip to content

Commit

Permalink
refactor implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
doroudi committed Sep 4, 2023
1 parent 2e21197 commit 9ad2b49
Show file tree
Hide file tree
Showing 27 changed files with 162 additions and 168 deletions.
Binary file removed ExcelMapper.Test/AppData/data.xlsx
Binary file not shown.
Binary file added ExcelMapper.Test/AppData/persons.xlsx
Binary file not shown.
18 changes: 10 additions & 8 deletions ExcelMapper.Test/MapperProfiles/EmployeeMapperProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,25 @@

namespace ExcelMapper.Test.MapperProfiles
{
public class EmployeeMapperProfile : ExcelImportMapper<Employee>
public class EmployeeMapperProfile : ExcelImportMapper<Person>
{
public EmployeeMapperProfile()
{
CreateMap()
.ForMember(x => x.Id,
opt => opt.MapFromCol("A").UseValidation(GeneralValidations.NotNull))
opt => opt.MapFromCol("A").UseValidation(Rules.NotNull))
.ForMember(x => x.Name,
opt => opt.MapFromCol("B").UseValidation(GeneralValidations.NotNull))
opt => opt.MapFromCol("B").UseValidation(Rules.NotNull))
.ForMember(x => x.Family,
opt => opt.MapFromCol("C").UseValidation(GeneralValidations.NotNull))
.ForMember(x => x.JoinDate,
opt => opt.MapFromCol("D").UseValidation(GeneralValidations.NotNull))
opt => opt.MapFromCol("C").UseValidation(Rules.NotNull))
.ForMember(x => x.BirthDate,
opt => opt.MapFromCol("D").IgnoreRegularEmptyValues().UseValidation(Rules.NotNull, Rules.Date))
.ForMember(x => x.NationalId,
opt => opt.MapFromCol("E").UseValidation(GeneralValidations.NotNull))
opt => opt.MapFromCol("E").UseValidation(Rules.NotNull))
.ForMember(x => x.Mobile,
opt => opt.MapFromCol("G"))
.ForMember(x => x.Address,
opt => opt.MapFromCol("F").UseValidation(GeneralValidations.NotNull));
opt => opt.MapFromCol("F").UseValidation(Rules.NotNull));
}
}
}
10 changes: 5 additions & 5 deletions ExcelMapper.Test/MapperProfiles/ExportProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@

namespace ExcelMapper.Test.MapperProfiles
{
public class ExportProfile: ExportMapper<Employee>
public class ExportProfile: ExportMapper<Person>
{
public ExportProfile(IWorkbook workbook): base(workbook)
{
CreateMap()
_ = CreateMap()
.ForColumn("A", x => x.Name, opt => opt.WithTitle("Name"))
.ForColumn("B", x => x.Family, opt => opt.WithTitle("Family"))
.ForColumn("C", x => x.BirthDate, opt => opt.WithTitle("BirthDate").UseAction(ConvertToPersian))
.ForColumn("D", x => x.Address, opt => opt.WithTitle("Address"))
.ForColumn("E", x => x.Name, opt => opt.WithTitle("NAME").UseAction(x => x.ToUpper()));
.ForColumn("E", x => x.Name, opt => opt.WithTitle("NAME").UseAction(x => x?.ToUpper()));
// .ForColumn("B", opt => opt.MapFrom<Employee>(x => x.Name));
}

private string ConvertToPersian(DateTime arg)
private string ConvertToPersian(DateTime? arg)
{
return arg.ToShortDateString();
return arg?.ToShortDateString() ?? "";
}
}
}
29 changes: 11 additions & 18 deletions ExcelMapper.Test/Models/Employee.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelMapper.Test.Models
namespace ExcelMapper.Test.Models
{
public class Employee
public record Person
{
public string Id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public string Mobile { get; set; }
public string NationalId { get; set; }
public string Address { get; set; }
public int Grade { get; set; }
public DateTime JoinDate { get; set; }
public DateTime BirthDate { get; set; }
public string? Id { get; set; }
public string? Name { get; set; }
public string? Family { get; set; }
public string? Mobile { get; set; }
public string? NationalId { get; set; }
public string? Address { get; set; }
public int? Grade { get; set; }
public DateTime? BirthDate { get; set; }

public override string ToString()
{
return $"({Name} {Family}, {BirthDate:D})";
return $"Name: {Name} {Family}, BirthDate:{BirthDate:D}, Mobile: {Mobile}";
}
}
}
19 changes: 9 additions & 10 deletions ExcelMapper.Test/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,23 @@
using ExcelMapper.Test.MapperProfiles;
using ExcelMapper.Test.Models;

var fileName = @"AppData\data.xlsx";
ExcelParser<Employee> parser = new (new FileInfo(fileName), new EmployeeMapperProfile());
var employees = parser.GetItems();
var fileName = @"AppData\persons.xlsx";
ExcelParser<Person> parser = new (new FileInfo(fileName), new EmployeeMapperProfile());
var people = parser.GetItems();


foreach (var emplyee in employees)
foreach (var person in people)
{
Console.WriteLine(emplyee);
Console.WriteLine(person);
}

// TODO: auto detect last column based on data
var logger = new ExcelLogger(fileName,"EF");
logger.LogInvalidColumns(parser.InvalidRows);
logger.LogInvalidColumns(parser.RowsState);

var exporter = new ExcelWriter();

exporter.AddSheet(
new ExportProfile(exporter.WorkBook),
x => x.SetRtl().UseData(employees).UseDefaultHeaderStyle().Build()
builder => builder.SetRtl().UseData(people).UseDefaultHeaderStyle().Build()
);

exporter.SaveToFile("D:\\excel\\EXPORT.xlsx");
exporter.SaveToFile("EXPORT.xlsx");
2 changes: 1 addition & 1 deletion ExcelMapper.Test/YummyCode.ExcelMapper.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
</ItemGroup>

<ItemGroup>
<None Update="AppData\data.xlsx">
<None Update="AppData\persons.xlsx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Expand Down
12 changes: 6 additions & 6 deletions ExcelMapper/ExcelExporter/ExportMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ namespace ExcelMapper.ExcelExporter
public ExportMapper(IWorkbook workbook)
{
_workbook = workbook;
_mappingExpression = new ExportMappingExpression<TSource>();
_compiledActions = new Dictionary<int, List<Delegate>>();
}

public List<CellMappingInfo> Mappings =>
Expand Down Expand Up @@ -44,12 +46,11 @@ public void Map(TSource data, IRow row)
SetCellValue(row, colMapping, converted);
}
//TODO Check
catch (Exception ex)
catch
{
throw;
}
}

}

private void CompileMappingActions()
Expand All @@ -68,9 +69,11 @@ private void CompileMappingActions()
}
}


private static void SetCellValue(IRow row, CellMappingInfo colMapping, object converted)
{
// TODO: should check for value is correct column name in excel
if (colMapping.Column < 0) return;

string cellValue = string.Empty;
if (colMapping.ConstValue != null)
cellValue = colMapping.ConstValue;
Expand All @@ -81,9 +84,6 @@ private static void SetCellValue(IRow row, CellMappingInfo colMapping, object co
else if (colMapping.DefaultValue != null)
cellValue = colMapping.DefaultValue;

// TODO: should check for value is correct column name in excel
if (colMapping.Column < 0) return;

var cell = row.CreateCell(colMapping.Column);
if (colMapping.Style != null)
cell.CellStyle = colMapping.Style;
Expand Down
4 changes: 2 additions & 2 deletions ExcelMapper/ExcelExporter/ExportMappingExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ namespace ExcelMapper.ExcelExporter
{
public class ExportMappingExpression<TDestination> : IExportMappingExpression<TDestination>
{
private readonly List<CellMappingInfo> _memberConfigurations =
new List<CellMappingInfo>();
private readonly List<CellMappingInfo> _memberConfigurations = new ();
private ICellStyle _defaultStyle;

public List<CellMappingInfo> Mappings => _memberConfigurations;
Expand All @@ -26,6 +25,7 @@ public IExportMappingExpression<TDestination> ForAllMembers

public IExportMappingExpression<TDestination> ForAllOtherMembers(Action<ExportConfigurationExpression<TDestination>> memberOptions)
{
// TODO: implement this
throw new NotImplementedException();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class ExportMemberConfigurationExpression<TDestination, TMember>
//public CellStyleOptions? CellStyle { get; private set; } = new CellStyleOptions();
public string? DefaultValue { get; private set; }
public string? ConstValue { get; private set; }
public List<LambdaExpression>? Actions { get; private set; } = new List<LambdaExpression>();
public List<LambdaExpression> Actions { get; private set; } = new List<LambdaExpression>();


// TODO: implement this
Expand Down
41 changes: 21 additions & 20 deletions ExcelMapper/ExcelLogger/ExcelLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,31 +44,32 @@ private void InitializeSourceFile()



public void LogInvalidColumns(Dictionary<int, Dictionary<string, CellErrorLevel>> invalidRows, int sheetIndex = 0)
public void LogInvalidColumns(Dictionary<IRow, ResultState> invalidRows, int sheetIndex = 0)
{
InitializeOutputFile();
InitializeStyles();
foreach (var row in invalidRows)
{
foreach (var col in row.Value)
{
_worksheet.Cell(col.Key, row.Key + 1)?.ApplyStyle(_warningStyle);
}
//foreach (var row in invalidRows)
//{

if (_resultCol != null)
{
var cell = _worksheet.Cell(_resultCol, row.Key + 1);
if (cell == null)
{
cell = _worksheet.GetRow(row.Key).CreateCell(_resultCol);
}
// foreach (var col in row.Key)
// {
// _worksheet.Cell(col.Row, row.Key + 1)?.ApplyStyle(_warningStyle);
// }

cell.SetCentered()
.ApplyStyle(_warningStyle)
.SetCellValue("Invalid");
// if (_resultCol != null)
// {
// var cell = _worksheet.Cell(_resultCol, row.Key + 1);
// if (cell == null)
// {
// cell = _worksheet.GetRow(row.Key).CreateCell(_resultCol);
// }

}
}
// cell.SetCentered()
// .ApplyStyle(_warningStyle)
// .SetCellValue("Invalid");

// }
//}
SaveExcelFile();
}

Expand All @@ -89,7 +90,7 @@ public void LogFailedRows(Dictionary<int, Exception> failedRows, string message
{
cell = _worksheet.GetRow(row.Key).CreateCell(_resultCol);
}
cell.Colorize(CellErrorLevel.Danger)
cell.Colorize(ResultState.Danger)
.SetCentered()
.SetCellValue(message);
}
Expand Down
27 changes: 23 additions & 4 deletions ExcelMapper/ExcelParser/ExcelParser{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ namespace ExcelMapper.ExcelParser
#region Fields
private readonly FileInfo _file;
private readonly ExcelImportMapper<TSource> _mapper;
private readonly Dictionary<IRow, ResultState> _rowsState = new();
private readonly int _sheetIndex;
#endregion

public Dictionary<int, Dictionary<string, CellErrorLevel>> InvalidRows;
//public Dictionary<int, Dictionary<string, CellState>> InvalidRows;
public bool IgnoreHeader { get; private set; } = true;

public FileInfo ActiveFile
Expand All @@ -33,7 +34,7 @@ public ExcelParser(FileInfo file, ExcelImportMapper<TSource> mapper, int sheetIn
{
_file = file;
_mapper = mapper;
InvalidRows = new Dictionary<int, Dictionary<string, CellErrorLevel>>();
//InvalidRows = new Dictionary<int, Dictionary<string, CellState>>();
_sheetIndex = sheetIndex;
}

Expand Down Expand Up @@ -67,14 +68,17 @@ public List<RowModel<TSource>> GetItems(int? take = null, int skip = 0)
try
{
var item = _mapper.Map(workSheet, row);
result.Add(new RowModel<TSource> (row.RowNum,item));
result.Add(new RowModel<TSource>(row.RowNum, item));
_rowsState.TryAdd(row, ResultState.Success);
}
catch (ExcelMappingException ex)
{
InvalidRows.Add(row.RowNum, ex.Cols);
_rowsState.TryAdd(row, ResultState.Warning);
//InvalidRows.Add(row.RowNum, ex.Cols);
}
catch (Exception ex)
{
_rowsState.TryAdd(row, ResultState.Warning);
WriteLine.Error($"error in converting data at row {row.RowNum} - {ex.Message}");
return;
}
Expand All @@ -83,6 +87,21 @@ public List<RowModel<TSource>> GetItems(int? take = null, int skip = 0)
return result;
}

public Dictionary<IRow, ResultState> RowsState
{
get
{
return _rowsState;
}
}

public IEnumerable<KeyValuePair<IRow, ResultState>> FailedRows
{
get
{
return _rowsState.Where(x => x.Value == ResultState.Warning);
}
}

#region Utilities
private ISheet InitializeExcelFile()
Expand Down
12 changes: 7 additions & 5 deletions ExcelMapper/Exceptions/CellExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ namespace ExcelMapper.Exceptions
{
public static class CellExtensions
{
public static ICell Colorize(this ICell @this, CellErrorLevel errorLevel)
public static ICell Colorize(this ICell @this, ResultState errorLevel)
{
if (@this == null) { return @this; }
if (@this == null)
throw new ArgumentNullException(nameof(@this));
@this.CellStyle.FillForegroundColor =
(errorLevel == CellErrorLevel.Danger) ?
(errorLevel == ResultState.Danger) ?
IndexedColors.Red.Index :
IndexedColors.Yellow.Index;
@this.CellStyle.FillPattern = FillPattern.SolidForeground;
Expand All @@ -32,7 +33,8 @@ public static ICell SetAlignment(this ICell @this, HorizontalAlignment alignment

public static ICell SetCentered(this ICell @this)
{
if (@this == null) { return @this; }
if (@this == null)
throw new ArgumentNullException(nameof(@this));
@this.CellStyle.Alignment = HorizontalAlignment.Center;
@this.CellStyle.VerticalAlignment = VerticalAlignment.Center;
return @this;
Expand All @@ -54,7 +56,7 @@ public static string GetValue(this ICell @this)
_ => @this.StringCellValue ?? @this.NumericCellValue.ToString()
};
}
catch (Exception ex)
catch
{
return @this.StringCellValue;
}
Expand Down
4 changes: 2 additions & 2 deletions ExcelMapper/Exceptions/ExcelMappingException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ namespace ExcelMapper.Exceptions
{
public class ExcelMappingException : Exception
{
public Dictionary<string, CellErrorLevel> Cols { get; set; }
public ExcelMappingException(Dictionary<string, CellErrorLevel> cols)
public Dictionary<string, ResultState> Cols { get; set; }
public ExcelMappingException(Dictionary<string, ResultState> cols)
{
Cols = cols;
}
Expand Down
1 change: 0 additions & 1 deletion ExcelMapper/Exceptions/SheetExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Text.RegularExpressions;

namespace ExcelMapper.Exceptions
{
Expand Down
Loading

0 comments on commit 9ad2b49

Please sign in to comment.