Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Add ExcelMapper sources to the project - add small changes

supportd82cf24748ad
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/ActionInvoker.cs b/src/Business/Grand.Business.Common/ExcelMapper/ActionInvoker.cs
new file mode 100644
index 000000000..68efdcaa4
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/ActionInvoker.cs
@@ -0,0 +1,67 @@
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Abstract class action invoker
+ /// </summary>
+ internal class ActionInvoker
+ {
+ /// <summary>
+ /// Invoke from an unspecified <paramref name="obj"/> type
+ /// </summary>
+ /// <param name="obj">mapping instance class</param>
+ /// <param name="index">index in the collection</param>
+ internal virtual void Invoke(object obj, int index) =>
+ throw new NotImplementedException();
+
+ /// <summary>
+ /// <see cref="ActionInvokerImpl{T}"/> factory
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="mappingAction"></param>
+ /// <returns></returns>
+ internal static ActionInvoker CreateInstance<T>(Action<T, int> mappingAction)
+ {
+ // instantiate concrete generic invoker
+ var invokerType = typeof(ActionInvokerImpl<>);
+ Type[] tType = { typeof(T) };
+ Type constructed = invokerType.MakeGenericType(tType);
+ object invokerInstance = Activator.CreateInstance(constructed, mappingAction);
+ return (ActionInvoker)invokerInstance;
+ }
+ }
+
+ /// <summary>
+ /// Generic form <see cref="ActionInvoker"/>
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ internal class ActionInvokerImpl<T> : ActionInvoker
+ where T : class
+ {
+ /// <summary>
+ /// ref to the mapping action.
+ /// </summary>
+ internal Action<T, int> mappingAction;
+
+ /// <summary>
+ /// Ctor
+ /// </summary>
+ /// <param name="mappingAction"></param>
+ public ActionInvokerImpl(Action<T, int> mappingAction)
+ {
+ this.mappingAction = mappingAction;
+ }
+
+ /// <summary>
+ /// Invoke Generic Action
+ /// </summary>
+ /// <param name="obj"></param>
+ /// <param name="index"></param>
+ internal override void Invoke(object obj, int index)
+ {
+ if (mappingAction is null || obj is null) return;
+ mappingAction((obj as T), index);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Attributes/ColumnAttribute.cs b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/ColumnAttribute.cs
new file mode 100644
index 000000000..545b9f7b1
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/ColumnAttribute.cs
@@ -0,0 +1,101 @@
+using NPOI.SS.Util;
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Attribute that specifies the mapping of a property to a column in an Excel file.
+ /// </summary>
+ /// <seealso cref="System.Attribute" />
+ [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
+ public sealed class ColumnAttribute : Attribute
+ {
+ readonly string name = null;
+ int index = -1;
+ readonly MappingDirections directions;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ColumnAttribute"/> class.
+ /// </summary>
+ /// <param name="name">The name of the column.</param>
+ /// <param name="directions">mapping direction</param>
+ public ColumnAttribute(string name, MappingDirections directions = MappingDirections.Both)
+ {
+ this.name = name;
+ this.directions = directions;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ColumnAttribute"/> class.
+ /// </summary>
+ /// <param name="index">The index of the column.</param>
+ /// <param name="directions">mapping direction</param>
+ public ColumnAttribute(int index, MappingDirections directions = MappingDirections.Both)
+ {
+ this.index = index;
+ this.directions = directions;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ColumnAttribute"/> class.
+ /// </summary>
+ /// <param name="index">The index of the column.</param>
+ /// <param name="name">The name of the column.</param>
+ /// <param name="directions">mapping direction</param>
+ public ColumnAttribute(int index, string name, MappingDirections directions = MappingDirections.Both)
+ {
+ this.index = index;
+ this.name = name;
+ this.directions = directions;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ColumnAttribute"/> class.
+ /// </summary>
+ /// <param name="directions">mapping direction</param>
+ public ColumnAttribute(MappingDirections directions = MappingDirections.Both)
+ {
+ this.directions = directions;
+ }
+
+ /// <summary>
+ /// Gets the direction of the column.
+ /// </summary>
+ /// <value>
+ /// The name of the column.
+ /// </value>
+ public MappingDirections Directions => directions;
+
+ /// <summary>
+ /// Gets the name of the column.
+ /// </summary>
+ /// <value>
+ /// The name of the column.
+ /// </value>
+ public string Name => name;
+
+ /// <summary>
+ /// Gets the index of the column.
+ /// </summary>
+ /// <value>
+ /// The index of the column.
+ /// </value>
+ public int Index => index;
+
+ /// <summary>
+ /// Gets or sets the column name in Excel letter format where A refers to column 1 etc.
+ /// </summary>
+ public string Letter
+ {
+ get => ExcelMapper.IndexToLetter(Index);
+ set => index = ExcelMapper.LetterToIndex(value);
+ }
+
+ /// <summary>
+ /// Gets or sets a value that indicates whether this attribute is inherited by derived classes.
+ /// It is useful if you want to prevent multiple mappings created by attributes in derived classes.
+ /// The default value is true.
+ /// </summary>
+ public bool Inherit { get; set; } = true;
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Attributes/DataFormatAttribute.cs b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/DataFormatAttribute.cs
new file mode 100644
index 000000000..a9c4705c3
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/DataFormatAttribute.cs
@@ -0,0 +1,48 @@
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Attribute that specifies the data format of an Excel cell.
+ /// The format can either be a <a href="https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html">builtin format</a>
+ /// or a <a href="https://support.office.com/en-nz/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4">custom format string</a>.
+ /// </summary>
+ /// <seealso cref="System.Attribute" />
+ [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
+ public sealed class DataFormatAttribute: Attribute
+ {
+ /// <summary>
+ /// Gets or sets the builtin format, see https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html for possible values.
+ /// </summary>
+ /// <value>
+ /// The builtin format.
+ /// </value>
+ public short BuiltinFormat { get; set; }
+
+ /// <summary>
+ /// Gets or sets the custom format, see https://support.office.com/en-nz/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 for the syntax.
+ /// </summary>
+ /// <value>
+ /// The custom format.
+ /// </value>
+ public string CustomFormat { get; set; }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataFormatAttribute"/> class.
+ /// </summary>
+ /// <param name="format">The format, see https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html for possible values.</param>
+ public DataFormatAttribute(short format)
+ {
+ BuiltinFormat = format;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataFormatAttribute"/> class.
+ /// </summary>
+ /// <param name="format">The format, see https://support.office.com/en-nz/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 for the syntax.</param>
+ public DataFormatAttribute(string format)
+ {
+ CustomFormat = format;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Attributes/FormulaAttribute.cs b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/FormulaAttribute.cs
new file mode 100644
index 000000000..3c04ab8c5
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/FormulaAttribute.cs
@@ -0,0 +1,14 @@
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Attribute which specifies that the property contains a formula.
+ /// This applies only to string properties and is only needed when saving Excel files.
+ /// </summary>
+ /// <seealso cref="System.Attribute" />
+ [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
+ public sealed class FormulaAttribute : Attribute
+ {
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Attributes/FormulaResultAttribute.cs b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/FormulaResultAttribute.cs
new file mode 100644
index 000000000..49c70c6d4
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/FormulaResultAttribute.cs
@@ -0,0 +1,14 @@
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Attribute which specifies that the formula result instead of the formula should be mapped.
+ /// This applies only to string properties, as for all other types the result will be mapped.
+ /// </summary>
+ /// <seealso cref="System.Attribute" />
+ [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
+ public sealed class FormulaResultAttribute : Attribute
+ {
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Attributes/IgnoreAttribute.cs b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/IgnoreAttribute.cs
new file mode 100644
index 000000000..413f26247
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/IgnoreAttribute.cs
@@ -0,0 +1,13 @@
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Attribute that specifies that a property should be ignored.
+ /// </summary>
+ /// <seealso cref="System.Attribute" />
+ [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
+ public sealed class IgnoreAttribute : Attribute
+ {
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Attributes/JsonAttribute.cs b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/JsonAttribute.cs
new file mode 100644
index 000000000..2ba449727
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Attributes/JsonAttribute.cs
@@ -0,0 +1,13 @@
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Attribute that specifies that the property should be serialized as JSON.
+ /// </summary>
+ /// <seealso cref="System.Attribute" />
+ [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
+ public sealed class JsonAttribute : Attribute
+ {
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/ColumnInfo.cs b/src/Business/Grand.Business.Common/ExcelMapper/ColumnInfo.cs
new file mode 100644
index 000000000..eca2eb0a8
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/ColumnInfo.cs
@@ -0,0 +1,539 @@
+using NPOI.SS.UserModel;
+using System;
+using System.Collections.Generic;
+using System.Dynamic;
+using System.Globalization;
+using System.Linq;
+using System.Reflection;
+using System.Text.Json;
+using Ganss.Excel.Exceptions;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Describes the mapping of a property to a cell in an Excel sheet.
+ /// </summary>
+ public class ColumnInfo
+ {
+ /// <summary>
+ /// Gets or sets the mapping directions.
+ /// </summary>
+ public MappingDirections Directions { get; internal set; } = MappingDirections.Both;
+
+ private PropertyInfo property;
+ private bool isSubType;
+
+ /// <summary>
+ /// Gets or sets the default cell setter.
+ /// </summary>
+ protected Action<ICell, object> defaultCellSetter;
+
+ /// <summary>
+ /// Gets or sets the custom cell setter.
+ /// </summary>
+ protected Action<ICell, object> customCellSetter;
+
+ /// <summary>
+ /// Sets the property type.
+ /// </summary>
+ /// <param name="propertyType">The property type.</param>
+ internal void SetPropertyType(Type propertyType)
+ {
+ if (propertyType.IsValueType)
+ {
+ var underlyingType = Nullable.GetUnderlyingType(propertyType);
+ IsNullable = underlyingType != null;
+ PropertyType = underlyingType ?? propertyType;
+ }
+ else
+ {
+ IsNullable = true;
+ PropertyType = propertyType;
+ }
+
+ isSubType = PropertyType != null
+ && !PropertyType.IsPrimitive
+ && !PropertyType.IsEnum
+ && PropertyType != typeof(decimal)
+ && PropertyType != typeof(string)
+ && PropertyType != typeof(DateTime)
+ && PropertyType != typeof(Guid)
+ && PropertyType != typeof(byte[]);
+ }
+
+ /// <summary>
+ /// Gets or sets the property name.
+ /// </summary>
+ public string Name { get; protected set; }
+
+ /// <summary>
+ /// Gets or sets the property.
+ /// </summary>
+ /// <value>
+ /// The property.
+ /// </value>
+ public PropertyInfo Property
+ {
+ get { return property; }
+ set
+ {
+ property = value;
+ if (property != null)
+ {
+ SetPropertyType(property.PropertyType);
+ Name = property.Name;
+ }
+ else
+ {
+ PropertyType = null;
+ IsNullable = false;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the mapped property has a nested type.
+ /// </summary>
+ public bool IsSubType
+ {
+ get
+ {
+ return isSubType && !Json
+ && SetProp == null;
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the property is nullable.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if the property is nullable; otherwise, <c>false</c>.
+ /// </value>
+ public bool IsNullable { get; protected set; }
+
+ /// <summary>
+ /// Gets the type of the property.
+ /// </summary>
+ /// <value>
+ /// The type of the property.
+ /// </value>
+ public Type PropertyType { get; protected set; }
+
+ /// <summary>
+ /// Gets or sets the cell setter.
+ /// </summary>
+ /// <value>
+ /// The cell setter.
+ /// </value>
+ public Action<ICell, object> SetCell => customCellSetter ?? defaultCellSetter;
+
+ /// <summary>
+ /// Gets or sets the property setter.
+ /// </summary>
+ /// <value>
+ /// The property setter.
+ /// </value>
+ public Func<object, object, ICell, object> SetProp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the builtin format.
+ /// </summary>
+ /// <value>
+ /// The builtin format.
+ /// </value>
+ public short BuiltinFormat { get; set; }
+
+ /// <summary>
+ /// Gets or sets the custom format.
+ /// </summary>
+ /// <value>
+ /// The custom format.
+ /// </value>
+ public string CustomFormat { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to map the formula result.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if the formula result will be mapped; otherwise, <c>false</c>.
+ /// </value>
+ public bool FormulaResult { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to save the property as a formula cell. Only needed when saving.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if the cell will contain a formula; otherwise, <c>false</c>.
+ /// </value>
+ public bool Formula { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to serialize as JSON.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if the property will be serialized as JSON; otherwise, <c>false</c>.
+ /// </value>
+ public bool Json { get; set; }
+
+ static readonly HashSet<Type> NumericTypes = new()
+ {
+ typeof(decimal),
+ typeof(byte), typeof(sbyte),
+ typeof(short), typeof(ushort),
+ typeof(int), typeof(uint),
+ typeof(long), typeof(ulong),
+ typeof(float), typeof(double)
+ };
+
+ /// <summary>
+ /// Generates the cell setter.
+ /// </summary>
+ /// <returns>The cell setter.</returns>
+ protected Action<ICell, object> GenerateCellSetter()
+ {
+ if (PropertyType == typeof(DateTime))
+ {
+ return (c, o) =>
+ {
+ if (o == null)
+ c.SetCellValue((string)null);
+ else
+ c.SetCellValue((DateTime)o);
+ };
+ }
+ else if (PropertyType == typeof(bool))
+ {
+ if (IsNullable)
+ return (c, o) =>
+ {
+ if (o == null)
+ c.SetCellValue((string)null);
+ else
+ c.SetCellValue((bool)o);
+ };
+ else
+ return (c, o) => c.SetCellValue((bool)o);
+ }
+ else if (NumericTypes.Contains(PropertyType))
+ {
+ if (IsNullable)
+ return (c, o) =>
+ {
+ if (o == null)
+ c.SetCellValue((string)null);
+ else
+ c.SetCellValue(Convert.ToDouble(o));
+ };
+ else
+ return (c, o) => c.SetCellValue(Convert.ToDouble(o));
+ }
+ else if (PropertyType == typeof(byte[]))
+ {
+ return (c, o) =>
+ {
+ if (o == null)
+ c.SetCellValue((string)null);
+ else
+ c.SetCellValue(System.Text.Encoding.UTF8.GetString((byte[])o));
+ };
+ }
+ else
+ {
+ return (c, o) =>
+ {
+ if (o == null)
+ c.SetCellValue((string)null);
+ else if (Formula)
+ c.SetCellFormula(o.ToString());
+ else if (!Json)
+ c.SetCellValue(o.ToString());
+ else
+ c.SetCellValue(JsonSerializer.Serialize(o));
+ };
+ }
+ }
+
+ /// <summary>Sets the column style.</summary>
+ /// <param name="sheet">The sheet.</param>
+ /// <param name="columnIndex">Index of the column.</param>
+ public void SetColumnStyle(ISheet sheet, int columnIndex)
+ {
+ if (BuiltinFormat != 0 || CustomFormat != null)
+ {
+ var wb = sheet.Workbook;
+ var cs = wb.CreateCellStyle();
+ if (CustomFormat != null)
+ cs.DataFormat = wb.CreateDataFormat().GetFormat(CustomFormat);
+ else
+ cs.DataFormat = BuiltinFormat;
+ sheet.SetDefaultColumnStyle(columnIndex, cs);
+ }
+ }
+
+ /// <summary>Sets the cell style.</summary>
+ /// <param name="c">The cell.</param>
+ public void SetCellStyle(ICell c)
+ {
+ if (BuiltinFormat != 0 || CustomFormat != null)
+ {
+ c.CellStyle = c.Sheet.GetColumnStyle(c.ColumnIndex);
+ //When it is a dynamic type, after initialization, if the first row is null and the dataformat is not set, the dataformat needs to be repaired again
+ if (c.CellStyle.DataFormat == 0)
+ {
+ SetColumnStyle(c.Sheet, c.ColumnIndex);
+ c.CellStyle = c.Sheet.GetColumnStyle(c.ColumnIndex);
+ }
+ }
+ }
+
+ private object ParseEnum(Type t, string s)
+ {
+ var name = Enum.GetNames(t).FirstOrDefault(n => n.Equals(s, StringComparison.OrdinalIgnoreCase));
+ return name == null ? Activator.CreateInstance(t) : Enum.Parse(t, name);
+ }
+
+ /// <summary>
+ /// Computes value that can be assigned to property from cell value.
+ /// </summary>
+ /// <param name="o">The object which contains the property.</param>
+ /// <param name="val">The value.</param>
+ /// <param name="cell">The cell where the value originates from.</param>
+ /// <returns>Value that can be assigned to property.</returns>
+ public virtual object GetPropertyValue(object o, object val, ICell cell)
+ {
+ object v;
+ if (SetProp != null)
+ v = SetProp(o, val, cell);
+ else if (IsNullable && (val == null || (val is string s && s.Length == 0)) && PropertyType == typeof(string)) //CHANGES FOR GRANDNODE
+ v = ""; //CHANGES FOR GRANDNODE
+ else if (IsNullable && (val == null || (val is string z && z.Length == 0)))
+ v = null;
+ else if (val is string g && PropertyType == typeof(Guid))
+ v = Guid.Parse(g);
+ else if (val is string es && PropertyType.IsEnum)
+ v = ParseEnum(PropertyType, es);
+ else if (val is string && PropertyType == typeof(byte[]))
+ v = System.Text.Encoding.UTF8.GetBytes(val as string);
+ else
+ v = Convert.ChangeType(val, PropertyType, CultureInfo.InvariantCulture);
+
+ return v;
+ }
+
+ /// <summary>
+ /// Sets the property of the specified object to the specified value.
+ /// </summary>
+ /// <param name="o">The object whose property to set.</param>
+ /// <param name="val">The value.</param>
+ /// <param name="cell">The cell where the value originates from.</param>
+ public virtual void SetProperty(object o, object val, ICell cell)
+ {
+ var v = GetPropertyValue(o, val, cell);
+ Property.SetValue(o, v, null);
+ }
+
+ /// <summary>
+ /// Gets the property value of the specified object.
+ /// </summary>
+ /// <param name="o">The object from which to get the property value.</param>
+ /// <returns>The property value.</returns>
+ public virtual object GetProperty(object o)
+ {
+ return Property.GetValue(o, null);
+ }
+
+ /// <summary>Specifies a method to use when setting the cell value from an object.</summary>
+ /// <param name="setCell">The method to use when setting the cell value from an object.</param>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo SetCellUsing(Action<ICell, object> setCell)
+ {
+ customCellSetter = setCell;
+ return this;
+ }
+
+ /// <summary>Specifies a method to use when setting the cell value from an object.</summary>
+ /// <param name="setCell">The method to use when setting the cell value from an object.</param>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo SetCellUsing<T>(Action<ICell, T> setCell)
+ {
+ customCellSetter = (c, o) => setCell(c, (T)o);
+ return this;
+ }
+
+ /// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
+ /// <param name="setProp">The method to use when setting the property value from the cell value.</param>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo SetPropertyUsing(Func<object, object> setProp)
+ {
+ SetProp = (o, v, c) => setProp(v);
+ return this;
+ }
+
+ /// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
+ /// <param name="setProp">The method to use when setting the property value from the cell value.</param>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo SetPropertyUsing(Func<object, ICell, object> setProp)
+ {
+ SetProp = (o, v, c) => setProp(v, c);
+ return this;
+ }
+
+ /// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
+ /// <param name="setProp">The method to use when setting the property value from the cell value.</param>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo SetPropertyUsing(Func<object, object, ICell, object> setProp)
+ {
+ SetProp = setProp;
+ return this;
+ }
+
+ /// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
+ /// <param name="setProp">The method to use when setting the property value from the cell value.</param>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo SetPropertyUsing<T>(Func<T, object, object> setProp)
+ {
+ SetProp = (o, v, c) => setProp((T)o, v);
+ return this;
+ }
+
+ /// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
+ /// <param name="setProp">The method to use when setting the property value from the cell value.</param>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo SetPropertyUsing<T>(Func<T, object, ICell, object> setProp)
+ {
+ SetProp = (o, v, c) => setProp((T)o, v, c);
+ return this;
+ }
+
+ /// <summary>Selects formula results to be mapped instead of the formula itself.</summary>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo AsFormulaResult()
+ {
+ FormulaResult = true;
+ return this;
+ }
+
+ /// <summary>Selects the property to be saved as a formula.</summary>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo AsFormula()
+ {
+ Formula = true;
+ return this;
+ }
+
+ /// <summary>Selects the property to be serialized as JSON.</summary>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo AsJson()
+ {
+ Json = true;
+ return this;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ColumnInfo"/> class.
+ /// </summary>
+ /// <param name="propertyInfo">The property information.</param>
+ /// <param name="direction">Data direction</param>
+ public ColumnInfo(PropertyInfo propertyInfo, MappingDirections direction = MappingDirections.Both)
+ {
+ Property = propertyInfo;
+ Directions = direction;
+ defaultCellSetter = GenerateCellSetter();
+ if (PropertyType == typeof(DateTime))
+ BuiltinFormat = 0x16; // "m/d/yy h:mm"
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ColumnInfo"/> class.
+ /// </summary>
+ protected ColumnInfo() { }
+
+ /// <summary>Selects the property to be unidirectional from Excel to Object.</summary>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo FromExcelOnly()
+ {
+ Directions = MappingDirections.ExcelToObject;
+ return this;
+ }
+
+ /// <summary>Selects the property to be unidirectional from Excel to Object.</summary>
+ /// <returns>The <see cref="ColumnInfo"/> object.</returns>
+ public ColumnInfo ToExcelOnly()
+ {
+ Directions = MappingDirections.ObjectToExcel;
+ return this;
+ }
+
+ internal void ChangeSetterType(Type newType)
+ {
+ SetPropertyType(newType);
+ defaultCellSetter = GenerateCellSetter();
+ if (PropertyType == typeof(DateTime))
+ BuiltinFormat = 0x16; // "m/d/yy h:mm"
+ else
+ {
+ BuiltinFormat = 0;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Describes the mapping of an <see cref="ExpandoObject"/>'s property to a cell.
+ /// </summary>
+ public class DynamicColumnInfo : ColumnInfo
+ {
+ /// <summary>
+ /// Gets or sets the column index.
+ /// </summary>
+ public int Index { get; set; }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DynamicColumnInfo"/> class.
+ /// </summary>
+ /// <param name="index">The column index.</param>
+ /// <param name="name">The column name.</param>
+ public DynamicColumnInfo(int index, string name)
+ {
+ Index = index;
+ Name = name;
+ FormulaResult = true;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DynamicColumnInfo"/> class.
+ /// </summary>
+ /// <param name="name">The column name.</param>
+ /// <param name="t">The type of the column.</param>
+ public DynamicColumnInfo(string name, Type t)
+ {
+ Name = name;
+ SetPropertyType(t);
+ defaultCellSetter = GenerateCellSetter();
+ if (PropertyType == typeof(DateTime))
+ BuiltinFormat = 0x16; // "m/d/yy h:mm"
+ }
+
+ /// <summary>
+ /// Sets the property of the specified object to the specified value.
+ /// </summary>
+ /// <param name="o">The object whose property to set.</param>
+ /// <param name="val">The value.</param>
+ /// <param name="cell">The cell where the value originates from.</param>
+ public override void SetProperty(object o, object val, ICell cell)
+ {
+ var expando = (IDictionary<string, object>)o;
+ if (!string.IsNullOrEmpty(Name))
+ expando.Add(Name, val);
+ }
+
+ /// <summary>
+ /// Gets the property value of the specified object.
+ /// </summary>
+ /// <param name="o">The o.</param>
+ /// <returns>The property value.</returns>
+ public override object GetProperty(object o)
+ {
+ return ((IDictionary<string, object>)o)[Name];
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/ColumnInfoDirections.cs b/src/Business/Grand.Business.Common/ExcelMapper/ColumnInfoDirections.cs
new file mode 100644
index 000000000..04dd4ba7d
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/ColumnInfoDirections.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Ganss.Excel
+{
+
+ /// <summary>
+ /// Data direction
+ /// </summary>
+ [Flags]
+ public enum MappingDirections
+ {
+ /// <summary>
+ /// From Excel to Object
+ /// </summary>
+ ExcelToObject = 1 << 0,
+ /// <summary>
+ /// From Object to Excel
+ /// </summary>
+ ObjectToExcel = 1 << 1,
+ /// <summary>
+ /// Both directions
+ /// </summary>
+ Both = ExcelToObject | ObjectToExcel,
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/EventArgs.cs b/src/Business/Grand.Business.Common/ExcelMapper/EventArgs.cs
new file mode 100644
index 000000000..0be1122cd
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/EventArgs.cs
@@ -0,0 +1,32 @@
+using NPOI.SS.UserModel;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Provides data for the <see cref="ExcelMapper.Saving"/> event.
+ /// </summary>
+ public class SavingEventArgs: EventArgs
+ {
+ /// <summary>
+ /// Gets or sets the sheet.
+ /// </summary>
+ /// <value>
+ /// The sheet.
+ /// </value>
+ public ISheet Sheet { get; private set; }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SavingEventArgs"/> class.
+ /// </summary>
+ /// <param name="sheet">The sheet that is being saved.</param>
+ public SavingEventArgs(ISheet sheet)
+ {
+ Sheet = sheet;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/ExcelMapper.cs b/src/Business/Grand.Business.Common/ExcelMapper/ExcelMapper.cs
new file mode 100644
index 000000000..0230085d0
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/ExcelMapper.cs
@@ -0,0 +1,1760 @@
+using Ganss.Excel.Exceptions;
+using NPOI.HSSF.UserModel;
+using NPOI.SS.UserModel;
+using NPOI.SS.Util;
+using NPOI.Util;
+using NPOI.XSSF.UserModel;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Dynamic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Reflection;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Map objects to Excel files.
+ /// </summary>
+ public class ExcelMapper
+ {
+ /// <summary>
+ /// Gets or sets the <see cref="TypeMapper"/> factory.
+ /// Default is a static <see cref="Ganss.Excel.TypeMapperFactory"/> object that caches <see cref="TypeMapper"/>s statically across <see cref="ExcelMapper"/> instances.
+ /// </summary>
+ /// <value>
+ /// The <see cref="TypeMapper"/> factory.
+ /// </value>
+ public ITypeMapperFactory TypeMapperFactory { get; set; } = DefaultTypeMapperFactory;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the Excel file contains a header row of column names. Default is <c>true</c>.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if the Excel file contains a header row; otherwise, <c>false</c>.
+ /// </value>
+ public bool HeaderRow { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the row number of the header row. Default is 0.
+ /// The header row may be outside of the range of <see cref="MinRowNumber"/> and <see cref="MaxRowNumber"/>.
+ /// </summary>
+ /// <value>
+ /// The header row number.
+ /// </value>
+ public int HeaderRowNumber { get; set; } = 0;
+
+ /// <summary>
+ /// Gets or sets the minimum row number of the rows that may contain data. Default is 0.
+ /// </summary>
+ /// <value>
+ /// The minimum row number.
+ /// </value>
+ public int MinRowNumber { get; set; } = 0;
+
+ /// <summary>
+ /// Gets or sets the inclusive maximum row number of the rows that may contain data. Default is <see cref="int.MaxValue"/>.
+ /// </summary>
+ /// <value>
+ /// The maximum row number.
+ /// </value>
+ public int MaxRowNumber { get; set; } = int.MaxValue;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to track objects read from the Excel file. Default is true.
+ /// If object tracking is enabled, the <see cref="ExcelMapper"/> object keeps track of objects it yields through the Fetch() methods.
+ /// You can then modify these objects and save them back to an Excel file without having to specify the list of objects to save.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if object tracking is enabled; otherwise, <c>false</c>.
+ /// </value>
+ public bool TrackObjects { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to skip blank rows when reading from Excel files. Default is true.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if blank lines are skipped; otherwise, <c>false</c>.
+ /// </value>
+ public bool SkipBlankRows { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to skip blank cells when reading from Excel files. Default is true.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if blank lines are skipped; otherwise, <c>false</c>.
+ /// </value>
+ public bool SkipBlankCells { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to create columns in existing Excel files for properties where
+ /// the corresponding header does not yet exist. If this is false and properties are mapped by name,
+ /// their corresponding headers must already be present in existing files.
+ /// Default is false.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if missing headers should be created; otherwise, <c>false</c>.
+ /// </value>
+ public bool CreateMissingHeaders { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to ignore nested types.
+ /// Default is false.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if nested types should be ignored; otherwise, <c>false</c>.
+ /// </value>
+ public bool IgnoreNestedTypes { get; set; }
+
+ /// <summary>
+ /// Gets or sets the <see cref="DataFormatter"/> object to use when formatting cell values.
+ /// </summary>
+ /// <value>
+ /// The <see cref="DataFormatter"/> object to use when formatting cell values.
+ /// </value>
+ public DataFormatter DataFormatter { get; set; } = new DataFormatter(CultureInfo.InvariantCulture);
+
+ /// <summary>
+ /// Occurs before saving and allows the workbook to be manipulated.
+ /// </summary>
+ public event EventHandler<SavingEventArgs> Saving;
+
+ /// <summary>
+ /// Occurs while parsing when value is not convertible.
+ /// Set Cancel to <c>true</c> to Cancel Exception, also, see <see cref="ParsingErrorEventArgs"/>
+ /// </summary>
+ public event EventHandler<ParsingErrorEventArgs> ErrorParsingCell;
+
+ private Func<string, string> NormalizeName { get; set; }
+
+ readonly Dictionary<Type, Func<object>> ObjectFactories = new();
+ Dictionary<string, Dictionary<int, object>> Objects { get; set; } = new();
+ IWorkbook Workbook { get; set; }
+
+ static readonly TypeMapperFactory DefaultTypeMapperFactory = new();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapper"/> class.
+ /// </summary>
+ public ExcelMapper() { }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapper"/> class.
+ /// </summary>
+ /// <param name="workbook">The workbook.</param>
+ public ExcelMapper(IWorkbook workbook)
+ {
+ Workbook = workbook;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapper"/> class.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ public ExcelMapper(string file)
+ {
+ Workbook = WorkbookFactory.Create(file);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapper"/> class.
+ /// </summary>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ public ExcelMapper(Stream stream)
+ {
+ Workbook = WorkbookFactory.Create(stream);
+ }
+
+ /// <summary>
+ /// Attaches the Excel file from the provided <see cref="IWorkbook"/>.
+ /// </summary>
+ /// <param name="workbook">The workbook.</param>
+ public void Attach(IWorkbook workbook)
+ {
+ Workbook = workbook;
+ }
+
+ /// <summary>
+ /// Attaches the Excel file from the provided path.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ public void Attach(string file)
+ {
+ Workbook = WorkbookFactory.Create(file);
+ }
+
+ /// <summary>
+ /// Attaches the Excel file read from the provided <see cref="Stream"/>.
+ /// </summary>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ public void Attach(Stream stream)
+ {
+ Workbook = WorkbookFactory.Create(stream);
+ }
+
+ /// <summary>
+ /// Sets a factory function to create objects of type <typeparamref name="T"/>.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to create.</typeparam>
+ /// <param name="factory">The factory function.</param>
+ public void CreateInstance<T>(Func<T> factory)
+ {
+ ObjectFactories[typeof (T)] = () => factory();
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<T> Fetch<T>(string file, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ return Fetch(file, typeof(T), sheetName, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable Fetch(string file, Type type, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(file);
+ return Fetch(type, sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<dynamic> Fetch(string file, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(file);
+ return Fetch(sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<T> Fetch<T>(string file, int sheetIndex, Func<string, object, object> valueParser = null)
+ {
+ return Fetch(file, typeof(T), sheetIndex, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable Fetch(string file, Type type, int sheetIndex, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(file);
+ return Fetch(type, sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<dynamic> Fetch(string file, int sheetIndex, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(file);
+ return Fetch(sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<T> Fetch<T>(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ return Fetch(stream, typeof(T), sheetName, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable Fetch(Stream stream, Type type, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(stream);
+ return Fetch(type, sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<dynamic> Fetch(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(stream);
+ return Fetch(sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<T> Fetch<T>(Stream stream, int sheetIndex, Func<string, object, object> valueParser = null)
+ {
+ return Fetch(stream, typeof(T), sheetIndex, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable Fetch(Stream stream, Type type, int sheetIndex, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(stream);
+ return Fetch(type, sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<dynamic> Fetch(Stream stream, int sheetIndex, Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(stream);
+ return Fetch(sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ /// <exception cref="System.ArgumentOutOfRangeException">Thrown when a sheet is not found</exception>
+ public IEnumerable<T> Fetch<T>(string sheetName, Func<string, object, object> valueParser = null)
+ {
+ return Fetch(typeof(T), sheetName, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ /// <exception cref="System.ArgumentOutOfRangeException">Thrown when a sheet is not found</exception>
+ public IEnumerable Fetch(Type type, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ PrimitiveCheck(type);
+
+ var sheet = Workbook.GetSheet(sheetName);
+ if (sheet == null)
+ {
+ throw new ArgumentOutOfRangeException(nameof(sheetName), sheetName, "Sheet not found");
+ }
+ return Fetch(sheet, type, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name.
+ /// </summary>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ /// <exception cref="System.ArgumentOutOfRangeException">Thrown when a sheet is not found</exception>
+ public IEnumerable<dynamic> Fetch(string sheetName, Func<string, object, object> valueParser = null)
+ {
+ var sheet = Workbook.GetSheet(sheetName);
+ if (sheet == null)
+ {
+ throw new ArgumentOutOfRangeException(nameof(sheetName), sheetName, "Sheet not found");
+ }
+ return Fetch(sheet, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<T> Fetch<T>(int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ var sheet = Workbook.GetSheetAt(sheetIndex);
+ return Fetch<T>(sheet, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable Fetch(Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ PrimitiveCheck(type);
+
+ var sheet = Workbook.GetSheetAt(sheetIndex);
+ return Fetch(sheet, type, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index.
+ /// </summary>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public IEnumerable<dynamic> Fetch(int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ var sheet = Workbook.GetSheetAt(sheetIndex);
+ return Fetch(sheet, valueParser);
+ }
+
+ IEnumerable<T> Fetch<T>(ISheet sheet, Func<string, object, object> valueParser = null)
+ {
+ return Fetch(sheet, typeof(T), valueParser).OfType<T>();
+ }
+
+ IEnumerable Fetch(ISheet sheet, Type type, Func<string, object, object> valueParser = null)
+ {
+ var firstRowNumber = HeaderRowNumber;
+
+ if (!HeaderRow)
+ firstRowNumber = sheet.Rows().Where(r => r.RowNum >= MinRowNumber && r.RowNum <= MaxRowNumber)
+ .OrderByDescending(r => r.LastCellNum).FirstOrDefault()?.RowNum ?? 0;
+
+ var firstRow = sheet.GetRow(firstRowNumber);
+
+ if (firstRow == null)
+ yield break;
+
+ var cells = Enumerable.Range(0, firstRow.LastCellNum).Select(i => firstRow.GetCell(i, MissingCellPolicy.RETURN_BLANK_AS_NULL));
+ var firstRowCells = cells
+ .Where(c => !HeaderRow || !string.IsNullOrWhiteSpace(c.ToString()));
+ var typeMapper = type != null ? TypeMapperFactory.Create(type) : TypeMapper.Create(firstRowCells, HeaderRow);
+
+ if (TrackObjects) Objects[sheet.SheetName] = new Dictionary<int, object>();
+
+ var objInstanceIdx = 0;
+
+ foreach (IRow row in sheet)
+ {
+ var i = row.RowNum;
+
+ if (i < MinRowNumber) continue;
+ if (i > MaxRowNumber) break;
+
+ // optionally skip header row and blank rows
+ if ((!HeaderRow || i != HeaderRowNumber) && (!SkipBlankRows || row.Cells.Any(c => !IsCellBlank(c))))
+ {
+ object o = MapCells(type, valueParser, typeMapper, firstRowCells, ref objInstanceIdx, row, new HashSet<Type> { type });
+ yield return o;
+ }
+ }
+ }
+
+ IEnumerable<dynamic> Fetch(ISheet sheet, Func<string, object, object> valueParser = null) =>
+ Fetch(sheet, type: null, valueParser).Cast<dynamic>();
+
+ private object MapCells(Type type, Func<string, object, object> valueParser, TypeMapper typeMapper,
+ IEnumerable<ICell> cells, ref int objInstanceIdx, IRow row, ISet<Type> callChain)
+ {
+ var sheet = row.Sheet;
+ var i = row.RowNum;
+ List<(ColumnInfo Col, object CellValue, ICell Cell, int ColumnIndex)> initValues = new();
+ var columns = cells
+ .Select(c => (Index: c.ColumnIndex,
+ Columns: GetColumnInfo(typeMapper, c).Where(c => c.Directions.HasFlag(MappingDirections.ExcelToObject) && !c.IsSubType).ToList()))
+ .Where(c => c.Columns.Any())
+ .ToList();
+
+ foreach (var (columnIndex, columnInfos) in columns)
+ {
+ var cell = row.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
+
+ if (cell != null && (!SkipBlankCells || !IsCellBlank(cell)))
+ {
+ foreach (var ci in columnInfos)
+ {
+ object cellValue;
+
+ try
+ {
+ cellValue = GetCellValue(cell, ci);
+ }
+ catch (Exception e)
+ {
+ cellValue = GetCellValue(cell);
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i, columnIndex, e));
+ }
+
+ try
+ {
+ if (valueParser != null)
+ cellValue = valueParser(string.IsNullOrWhiteSpace(ci.Name) ? columnIndex.ToString() : ci.Name, cellValue);
+
+ initValues.Add((ci, cellValue, cell, columnIndex));
+ }
+ catch (Exception e)
+ {
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i, columnIndex, e));
+ }
+ }
+ }
+ }
+
+ if (!IgnoreNestedTypes)
+ {
+ foreach (var ci in typeMapper.ColumnsByName.SelectMany(c => c.Value).Where(c => c.IsSubType))
+ {
+ if (!callChain.Contains(ci.PropertyType) // check for cycle in type hierarchy
+ && !initValues.Any(v => v.Col.Property.IsIdenticalTo(ci.Property))) // map subtypes only if not already mapped
+ {
+ callChain.Add(ci.PropertyType);
+ var subTypeMapper = TypeMapperFactory.Create(ci.PropertyType);
+ var subObject = MapCells(ci.PropertyType, valueParser, subTypeMapper, cells, ref objInstanceIdx, row, callChain);
+ initValues.Add((ci, subObject, null, -1));
+ }
+ }
+ }
+
+ object o;
+
+ if (type == null)
+ o = typeMapper.CreateExpando();
+ else
+ {
+ if (typeMapper.Constructor != null)
+ {
+ var parms = typeMapper.Constructor.GetParameters();
+ var vals = parms.Select(p => GetDefault(p.ParameterType)).ToArray();
+
+ foreach (var initVal in initValues.ToList())
+ {
+ if (typeMapper.ConstructorParams.TryGetValue(initVal.Col.Property.Name, out var parm))
+ {
+ try
+ {
+ object v;
+
+ if (initVal.Cell != null)
+ v = initVal.Col.GetPropertyValue(null, initVal.CellValue, initVal.Cell);
+ else
+ v = initVal.CellValue;
+
+ vals[parm.Position] = v;
+
+ initValues.Remove(initVal);
+ }
+ catch (Exception ex)
+ {
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(initVal.CellValue, initVal.Col.PropertyType, i, initVal.ColumnIndex, ex));
+ }
+ }
+ }
+
+ try
+ {
+ o = typeMapper.Constructor.Invoke(vals);
+ }
+ catch (Exception ex)
+ {
+ throw new ExcelMapperConvertException($"Failed to initialize type {type.FullName}.", ex);
+ }
+ }
+ else
+ {
+ if (ObjectFactories.TryGetValue(type, out var factory))
+ {
+ o = factory();
+ }
+ else
+ {
+ try
+ {
+ o = Activator.CreateInstance(type);
+ }
+ catch (Exception)
+ {
+ o = null;
+ }
+ }
+
+ if (o == null)
+ return null;
+ }
+ }
+
+ if (initValues.Any())
+ {
+ typeMapper?.BeforeMappingActionInvoker?.Invoke(o, objInstanceIdx);
+
+ foreach (var val in initValues)
+ {
+ try
+ {
+ if (val.Cell != null)
+ val.Col.SetProperty(o, val.CellValue, val.Cell);
+ else
+ val.Col.Property.SetValue(o, val.CellValue);
+ }
+ catch (Exception ex)
+ {
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(val.CellValue, val.Col.PropertyType, i, val.ColumnIndex, ex));
+ }
+ }
+ }
+ if (TrackObjects) Objects[sheet.SheetName][i] = o;
+
+ typeMapper?.AfterMappingActionInvoker?.Invoke(o, objInstanceIdx);
+
+ objInstanceIdx++;
+ return o;
+ }
+
+ private void TriggerOrThrowParsingError(ExcelMapperConvertException excelMapperConvertException)
+ {
+ var parsingError = new ParsingErrorEventArgs(excelMapperConvertException);
+ ErrorParsingCell?.Invoke(this, parsingError);
+ if (!parsingError.Cancel)
+ throw excelMapperConvertException;
+ }
+
+ static object GetDefault(Type t) => t.GetTypeInfo().IsValueType ? Activator.CreateInstance(t) : null;
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<T>> FetchAsync<T>(string file, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ return (await FetchAsync(file, typeof(T), sheetName, valueParser)).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches dynamic objects from the specified sheet name using async I/O.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<dynamic>> FetchAsync(string file, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(file);
+ return Fetch(ms, sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name using async I/O.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable> FetchAsync(string file, Type type, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(file);
+ return Fetch(ms, type, sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<T>> FetchAsync<T>(string file, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(file);
+ return Fetch(ms, typeof(T), sheetIndex, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches dynamic objects from the specified sheet index using async I/O.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<dynamic>> FetchAsync(string file, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(file);
+ return Fetch(ms, sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index using async I/O.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable> FetchAsync(string file, Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(file);
+ return Fetch(ms, type, sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<T>> FetchAsync<T>(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(stream);
+ return Fetch(ms, typeof(T), sheetName, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches dynamic objects from the specified sheet name using async I/O.
+ /// </summary>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<dynamic>> FetchAsync(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(stream);
+ return Fetch(ms, sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet name using async I/O.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable> FetchAsync(Stream stream, Type type, string sheetName, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(stream);
+ return Fetch(ms, type, sheetName, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<T>> FetchAsync<T>(Stream stream, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(stream);
+ return Fetch(ms, typeof(T), sheetIndex, valueParser).OfType<T>();
+ }
+
+ /// <summary>
+ /// Fetches dynamic objects from the specified sheet index using async I/O.
+ /// </summary>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable<dynamic>> FetchAsync(Stream stream, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(stream);
+ return Fetch(ms, sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches objects from the specified sheet index using async I/O.
+ /// </summary>
+ /// <param name="type">The type of objects the Excel file is mapped to.</param>
+ /// <param name="stream">The stream the Excel file is read from.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="valueParser">Allow value parsing</param>
+ /// <returns>The objects read from the Excel file.</returns>
+ public async Task<IEnumerable> FetchAsync(Stream stream, Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(stream);
+ return Fetch(ms, type, sheetIndex, valueParser);
+ }
+
+ /// <summary>
+ /// Fetches the names of all sheets.
+ /// </summary>
+ /// <returns>The sheet names.</returns>
+ public IEnumerable<string> FetchSheetNames() => Workbook == null ? Array.Empty<string>() : Enumerable.Range(0, Workbook.NumberOfSheets).Select(i => Workbook.GetSheetName(i));
+
+ static async Task<Stream> ReadAsync(string file)
+ {
+ using var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
+ var ms = new MemoryStream();
+ await fs.CopyToAsync(ms);
+ return ms;
+ }
+
+ static async Task<Stream> ReadAsync(Stream stream)
+ {
+ var ms = new MemoryStream();
+ await stream.CopyToAsync(ms);
+ return ms;
+ }
+
+ private static bool IsCellBlank(ICell cell)
+ {
+ return cell.CellType switch
+ {
+ CellType.String => string.IsNullOrWhiteSpace(cell.StringCellValue),
+ CellType.Blank => true,
+ _ => false,
+ };
+ }
+
+ List<ColumnInfo> GetColumnInfo(TypeMapper typeMapper, ICell cell)
+ {
+ var colByIndex = typeMapper.GetColumnByIndex(cell.ColumnIndex);
+
+ if (!HeaderRow || colByIndex != null)
+ return colByIndex ?? new();
+
+ var name = cell.ToString();
+ var normalizedName = NormalizeCellName(typeMapper, name);
+ var colByName = typeMapper.GetColumnByName(normalizedName);
+
+ // map column by name only if it hasn't been mapped to another property by index
+ if (colByName != null
+ && !typeMapper.ColumnsByIndex.SelectMany(ci => ci.Value).Any(c => c.Property.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
+ return colByName;
+
+ return new();
+ }
+
+ private string NormalizeCellName(TypeMapper typeMapper, string name)
+ {
+ if (typeMapper.NormalizeName != null) return typeMapper.NormalizeName(name);
+ else if (NormalizeName != null) return NormalizeName(name);
+ return name;
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified Excel file.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save<T>(string file, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
+ Save(fs, objects, sheetName, xlsx, valueConverter);
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified Excel file.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save<T>(string file, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
+ Save(fs, objects, sheetIndex, xlsx, valueConverter);
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified stream.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save<T>(Stream stream, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
+ var sheet = Workbook.GetSheet(sheetName);
+ sheet ??= Workbook.CreateSheet(sheetName);
+ Save(stream, sheet, objects, valueConverter);
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified stream.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save<T>(Stream stream, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
+ ISheet sheet;
+ if (Workbook.NumberOfSheets > sheetIndex)
+ sheet = Workbook.GetSheetAt(sheetIndex);
+ else
+ sheet = Workbook.CreateSheet();
+ Save(stream, sheet, objects, valueConverter);
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified Excel file.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save(string file, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
+ Save(fs, sheetName, xlsx, valueConverter);
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified Excel file.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save(string file, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
+ Save(fs, sheetIndex, xlsx, valueConverter);
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save(Stream stream, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
+ var sheet = Workbook.GetSheet(sheetName);
+ sheet ??= Workbook.CreateSheet(sheetName);
+ Save(stream, sheet, valueConverter);
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public void Save(Stream stream, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
+ var sheet = Workbook.GetSheetAt(sheetIndex);
+ sheet ??= Workbook.CreateSheet();
+ Save(stream, sheet, valueConverter);
+ }
+
+ void Save(Stream stream, ISheet sheet, Func<string, object, object> valueConverter = null)
+ {
+ var objects = Objects[sheet.SheetName];
+ var typeMapper = TypeMapperFactory.Create(objects.First().Value);
+ var columnsByIndex = typeMapper.ColumnsByIndex;
+
+ columnsByIndex = columnsByIndex.Where(kvp => !kvp.Value.All(ci => ci.Directions == MappingDirections.ExcelToObject))
+ .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
+
+ GetColumns(sheet, typeMapper, columnsByIndex);
+
+ SetColumnStyles(sheet, columnsByIndex);
+
+ foreach (var o in objects)
+ {
+ var i = o.Key;
+ var row = sheet.GetRow(i);
+ row ??= sheet.CreateRow(i);
+
+ SetCells(typeMapper, columnsByIndex, o.Value, row, valueConverter);
+ }
+
+ Saving?.Invoke(this, new SavingEventArgs(sheet));
+
+ Workbook.Write(stream, leaveOpen: true);
+ }
+
+ void Save<T>(Stream stream, ISheet sheet, IEnumerable<T> objects, Func<string, object, object> valueConverter = null)
+ {
+ var firstObject = objects.FirstOrDefault();
+ var typeMapper = firstObject is ExpandoObject ? TypeMapperFactory.Create(firstObject) : TypeMapperFactory.Create(typeof(T));
+ var columnsByIndex = typeMapper.ColumnsByIndex;
+ var i = MinRowNumber;
+
+ columnsByIndex = columnsByIndex.Where(kvp => !kvp.Value.All(ci => ci.Directions == MappingDirections.ExcelToObject))
+ .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
+
+ GetColumns(sheet, typeMapper, columnsByIndex);
+
+ SetColumnStyles(sheet, columnsByIndex);
+
+ foreach (var o in objects)
+ {
+ if (i > MaxRowNumber) break;
+
+ if (HeaderRow && i == HeaderRowNumber)
+ i++;
+
+ var row = sheet.GetRow(i);
+ row ??= sheet.CreateRow(i);
+
+ SetCells(typeMapper, columnsByIndex, o, row, valueConverter);
+
+ i++;
+ }
+
+ if (SkipBlankCells)
+ {
+ while (i <= sheet.LastRowNum && i <= MaxRowNumber)
+ {
+ var row = sheet.GetRow(i);
+ while (row.Cells.Any())
+ row.RemoveCell(row.GetCell(row.FirstCellNum));
+ i++;
+ }
+ }
+
+ Saving?.Invoke(this, new SavingEventArgs(sheet));
+
+ Workbook.Write(stream, leaveOpen: true);
+ }
+
+ private void SetCells(TypeMapper typeMapper,
+ Dictionary<int, List<ColumnInfo>> columnsByIndex,
+ object o, IRow row,
+ Func<string, object, object> valueConverter = null)
+ {
+ var columnsByName = typeMapper.ColumnsByName;
+
+ foreach (var col in columnsByIndex)
+ {
+ var cell = row.GetCell(col.Key, MissingCellPolicy.CREATE_NULL_AS_BLANK);
+
+ foreach (var ci in col.Value.Where(c => (c is DynamicColumnInfo)
+ || (c.Directions.HasFlag(MappingDirections.ObjectToExcel)
+ && (c?.Property?.DeclaringType.IsAssignableFrom(typeMapper.Type) == true))))
+ {
+ SetCell(valueConverter, o, cell, ci);
+ }
+ }
+
+ if (!IgnoreNestedTypes)
+ {
+ foreach (var col in columnsByName.SelectMany(c => c.Value.Where(c => c.Directions.HasFlag(MappingDirections.ObjectToExcel) && c.IsSubType)))
+ {
+ var subTypeMapper = TypeMapperFactory.Create(col.PropertyType);
+ var subObject = col.Property.GetValue(o);
+
+ if (subObject != null)
+ {
+ SetCells(subTypeMapper, columnsByIndex, subObject, row, valueConverter);
+ }
+ }
+ }
+ }
+
+ private static void SetCell<T>(Func<string, object, object> valueConverter, T objInstance, ICell cell, ColumnInfo ci)
+ {
+ Type oldType = null;
+ object val = ci.GetProperty(objInstance);
+ if (valueConverter != null)
+ {
+ val = valueConverter(ci.Name, val);
+ }
+ //When the value is a dynamic type or has a specified value conversion function, the type may be inconsistent, and the type needs to be changed
+ var newType = val?.GetType() ?? ci.PropertyType;
+ if (newType != ci.PropertyType)
+ {
+ oldType = ci.PropertyType;
+ ci.ChangeSetterType(newType);
+ }
+ ci.SetCellStyle(cell);
+ ci.SetCell(cell, val);
+ if (oldType != null)
+ ci.ChangeSetterType(oldType);
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified Excel file using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync<T>(string file, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, objects, sheetName, xlsx, valueConverter);
+ await SaveAsync(file, ms.ToArray());
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified Excel file using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync<T>(string file, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, objects, sheetIndex, xlsx, valueConverter);
+ await SaveAsync(file, ms.ToArray());
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified stream using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync<T>(Stream stream, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, objects, sheetName, xlsx, valueConverter);
+ await SaveAsync(stream, ms);
+ }
+
+ /// <summary>
+ /// Saves the specified objects to the specified stream using async I/O.
+ /// </summary>
+ /// <typeparam name="T">The type of objects to save.</typeparam>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="objects">The objects to save.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync<T>(Stream stream, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, objects, sheetIndex, xlsx, valueConverter);
+ await SaveAsync(stream, ms);
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified Excel file using async I/O.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync(string file, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, sheetName, xlsx, valueConverter);
+ await SaveAsync(file, ms.ToArray());
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified Excel file using async I/O.
+ /// </summary>
+ /// <param name="file">The path to the Excel file.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync(string file, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, sheetIndex, xlsx, valueConverter);
+ await SaveAsync(file, ms.ToArray());
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified stream using async I/O.
+ /// </summary>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="sheetName">Name of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync(Stream stream, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, sheetName, xlsx, valueConverter);
+ await SaveAsync(stream, ms);
+ }
+
+ /// <summary>
+ /// Saves tracked objects to the specified stream using async I/O.
+ /// </summary>
+ /// <param name="stream">The stream to save the objects to.</param>
+ /// <param name="sheetIndex">Index of the sheet.</param>
+ /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
+ /// <param name="valueConverter">converter receiving property name and value</param>
+ public async Task SaveAsync(Stream stream, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
+ {
+ using var ms = new MemoryStream();
+ Save(ms, sheetIndex, xlsx, valueConverter);
+ await SaveAsync(stream, ms);
+ }
+
+ static async Task SaveAsync(string file, byte[] buf)
+ {
+ using var fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
+ await fs.WriteAsync(buf, 0, buf.Length);
+ }
+
+ static async Task SaveAsync(Stream stream, MemoryStream ms)
+ {
+ var buf = ms.ToArray();
+ await stream.WriteAsync(buf, 0, buf.Length);
+ }
+
+ static void SetColumnStyles(ISheet sheet, Dictionary<int, List<ColumnInfo>> columnsByIndex)
+ {
+ foreach (var col in columnsByIndex)
+ col.Value.Where(c => c.Directions.HasFlag(MappingDirections.ObjectToExcel))
+ .ToList().ForEach(ci => ci.SetColumnStyle(sheet, col.Key));
+ }
+
+ void GetColumns(ISheet sheet, TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex)
+ {
+ var callChain = new HashSet<Type> { typeMapper.Type };
+
+ if (HeaderRow)
+ {
+ var headerRow = sheet.GetRow(HeaderRowNumber);
+
+ if (headerRow == null)
+ {
+ headerRow = sheet.CreateRow(HeaderRowNumber);
+ var columnIndex = 0;
+ PopulateHeaderRow(typeMapper, columnsByIndex, headerRow, ref columnIndex, callChain);
+ }
+ else
+ {
+ if (CreateMissingHeaders)
+ {
+ UpdateHeaderRow(typeMapper, columnsByIndex, headerRow, callChain);
+ }
+ else
+ {
+ ReadHeaderRow(typeMapper, columnsByIndex, headerRow, callChain);
+ }
+ }
+ }
+ else
+ {
+ columnsByIndex.Clear();
+ GatherColumnIndexes(typeMapper, columnsByIndex, callChain);
+ }
+ }
+
+ private void GatherColumnIndexes(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex, ISet<Type> callChain)
+ {
+ var columnsByName = typeMapper.ColumnsByName;
+
+ foreach (var (index, columns) in typeMapper.ColumnsByIndex.Select(p => (Index: p.Key,
+ Columns: p.Value.Where(c => c.Directions != MappingDirections.ExcelToObject && !c.IsSubType))))
+ {
+ if (!columnsByIndex.TryGetValue(index, out var columnInfos))
+ columnsByIndex[index] = columnInfos = new();
+ columnInfos.AddRange(columns);
+ }
+
+ if (!IgnoreNestedTypes)
+ {
+ foreach (var propertyType in columnsByName.SelectMany(c => c.Value.Where(c => c.Directions != MappingDirections.ExcelToObject && c.IsSubType))
+ .Select(c => c.PropertyType))
+ {
+ if (!callChain.Contains(propertyType))
+ {
+ callChain.Add(propertyType);
+ var subTypeMapper = TypeMapperFactory.Create(propertyType);
+ GatherColumnIndexes(subTypeMapper, columnsByIndex, callChain);
+ }
+ }
+ }
+ }
+
+ private void UpdateHeaderRow(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex, IRow headerRow, ISet<Type> callChain)
+ {
+ var columnsByName = typeMapper.ColumnsByName;
+
+ foreach (var col in columnsByName)
+ {
+ foreach (var columnInfo in col.Value.Where(c => c.Directions != MappingDirections.ExcelToObject))
+ {
+ if (!columnInfo.IsSubType)
+ {
+ var columnInfoByIndex = columnsByIndex.FirstOrDefault(c => c.Value.Any(v =>
+ v.Directions != MappingDirections.ObjectToExcel && v.Property.IsIdenticalTo(columnInfo.Property)));
+ var columnIndex = 0;
+
+ if (columnInfoByIndex.Value == null)
+ {
+ for (; columnIndex < headerRow.LastCellNum; columnIndex++)
+ {
+ var c = headerRow.GetCell(columnIndex, MissingCellPolicy.RETURN_BLANK_AS_NULL);
+ if (c == null || string.IsNullOrEmpty(c.ToString()))
+ break;
+ }
+ }
+ else
+ {
+ columnIndex = columnInfoByIndex.Key;
+ }
+
+ var cell = headerRow.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
+ columnsByIndex[columnIndex] = col.Value;
+ cell.SetCellValue(col.Key);
+ }
+ else if (!IgnoreNestedTypes && !callChain.Contains(columnInfo.PropertyType))
+ {
+ callChain.Add(columnInfo.PropertyType);
+ var subTypeMapper = TypeMapperFactory.Create(columnInfo.PropertyType);
+ UpdateHeaderRow(subTypeMapper, columnsByIndex, headerRow, callChain);
+ }
+ }
+ }
+ }
+
+ private void ReadHeaderRow(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex, IRow headerRow, ISet<Type> callChain)
+ {
+ foreach (var cols in headerRow.Cells
+ .Where(c => !string.IsNullOrWhiteSpace(c.ToString()))
+ .Select(c =>
+ {
+ var name = c.ToString();
+ var normalizedName = NormalizeCellName(typeMapper, name);
+ var val = new { c.ColumnIndex, ColumnInfo = typeMapper.GetColumnByName(normalizedName), ColumnName = c.ToString() };
+ return val;
+ })
+ .Where(c => c.ColumnInfo != null))
+ {
+ var columnIndex = cols.ColumnIndex;
+ if (!columnsByIndex.TryGetValue(columnIndex, out var columnInfos))
+ columnsByIndex[columnIndex] = columnInfos = new();
+
+ foreach (var col in cols.ColumnInfo.Where(c => c.Directions != MappingDirections.ExcelToObject && !c.IsSubType))
+ {
+ columnInfos.Add(col);
+ }
+ }
+
+ if (!IgnoreNestedTypes)
+ {
+ foreach (var columns in typeMapper.ColumnsByName)
+ {
+ foreach (var propertyType in columns.Value.Where(c => c.IsSubType && !callChain.Contains(c.PropertyType))
+ .Select(c => c.PropertyType))
+ {
+ callChain.Add(propertyType);
+ var subTypeMapper = TypeMapperFactory.Create(propertyType);
+ ReadHeaderRow(subTypeMapper, columnsByIndex, headerRow, callChain);
+ }
+ }
+ }
+ }
+
+ private void PopulateHeaderRow(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex,
+ IRow headerRow, ref int columnIndex, ISet<Type> callChain)
+ {
+ var typeColumnsByName = typeMapper.ColumnsByName;
+ var typeColumnsByIndex = typeMapper.ColumnsByIndex;
+
+ foreach (var columns in typeColumnsByName)
+ {
+ var noSubTypeColumns = columns.Value.Where(c => !c.IsSubType && c.Directions != MappingDirections.ExcelToObject).ToList();
+
+ if (noSubTypeColumns.Any())
+ {
+ var columnIndexes = typeColumnsByIndex.Where(c =>
+ c.Value.Any(v => v.Directions != MappingDirections.ExcelToObject && noSubTypeColumns.Any(n => n.Name == v.Name)))
+ .Select(c => c.Key);
+
+ if (columnIndexes.Any())
+ {
+ columnIndex = columnIndexes.First();
+ }
+ else
+ {
+ if (!columnsByIndex.TryGetValue(columnIndex, out var columnInfos))
+ columnsByIndex[columnIndex] = noSubTypeColumns;
+ else
+ columnInfos.AddRange(noSubTypeColumns);
+ }
+
+ var cell = headerRow.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
+
+ cell.SetCellValue(columns.Key);
+
+ columnIndex++;
+ }
+
+ if (!IgnoreNestedTypes)
+ {
+ foreach (var propertyType in columns.Value.Where(c => c.IsSubType && !callChain.Contains(c.PropertyType))
+ .Select(c => c.PropertyType))
+ {
+ callChain.Add(propertyType);
+ var subTypeMapper = TypeMapperFactory.Create(propertyType);
+ PopulateHeaderRow(subTypeMapper, columnsByIndex, headerRow, ref columnIndex, callChain);
+ }
+ }
+ }
+ }
+
+ object GetCellValue(ICell cell, ColumnInfo targetColumn)
+ {
+ var formulaResult = cell.CellType == CellType.Formula && (targetColumn.PropertyType != typeof(string) || targetColumn.FormulaResult);
+ var cellType = formulaResult ? cell.CachedFormulaResultType : cell.CellType;
+ const int maxDate = 2958465; // 31/12/9999
+
+ switch (cellType)
+ {
+ case CellType.Numeric:
+ if (!formulaResult && targetColumn.PropertyType == typeof(string))
+ {
+ return DataFormatter.FormatCellValue(cell);
+ }
+ else if (cell.NumericCellValue < maxDate && DateUtil.IsCellDateFormatted(cell))
+ {
+ return cell.DateCellValue;
+ }
+ else
+ return cell.NumericCellValue;
+ case CellType.Formula:
+ return cell.CellFormula;
+ case CellType.Boolean:
+ return cell.BooleanCellValue;
+ case CellType.Error:
+ return cell.ErrorCellValue;
+ case CellType.Unknown:
+ case CellType.Blank:
+ case CellType.String:
+ default:
+ if (targetColumn.Json)
+ return JsonSerializer.Deserialize(cell.StringCellValue, targetColumn.PropertyType);
+ else
+ return cell.StringCellValue;
+ }
+ }
+
+ object GetCellValue(ICell cell)
+ {
+ return cell.CellType switch
+ {
+ CellType.Numeric => cell.NumericCellValue,
+ CellType.Formula => cell.CellFormula,
+ CellType.Boolean => cell.BooleanCellValue,
+ CellType.Error => cell.ErrorCellValue,
+ CellType.String => cell.StringCellValue,
+ CellType.Blank => string.Empty,
+ _ => "<unknown>",
+ };
+ }
+
+ static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> propertyExpression)
+ {
+ var exp = (LambdaExpression)propertyExpression;
+ var mExp = (exp.Body.NodeType == ExpressionType.MemberAccess) ?
+ (MemberExpression)exp.Body :
+ (MemberExpression)((UnaryExpression)exp.Body).Operand;
+ return (PropertyInfo)mExp.Member;
+ }
+
+ static void PrimitiveCheck(Type type)
+ {
+ if (type.IsPrimitive || typeof(string).Equals(type) || typeof(object).Equals(type) || Nullable.GetUnderlyingType(type) != null)
+ {
+ throw new ArgumentException($"{type.Name} can not be used to map an excel because it is a primitive type");
+ }
+ }
+
+ /// <summary>
+ /// Action to call after an object is mapped
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="action"></param>
+ /// <returns></returns>
+ public ExcelMapper AddAfterMapping<T>(Action<T, int> action)
+ {
+ var typeMapper = TypeMapperFactory.Create(typeof(T));
+ typeMapper.AfterMappingActionInvoker = ActionInvoker.CreateInstance(action);
+ return this;
+ }
+
+ /// <summary>
+ /// Action to call before an object is mapped
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="action"></param>
+ /// <returns></returns>
+ public ExcelMapper AddBeforeMapping<T>(Action<T, int> action)
+ {
+ var typeMapper = TypeMapperFactory.Create(typeof(T));
+ typeMapper.BeforeMappingActionInvoker = ActionInvoker.CreateInstance(action);
+ return this;
+ }
+
+ /// <summary>
+ /// Adds a mapping from a column name to a property.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="columnName">Name of the column.</param>
+ /// <param name="propertyExpression">The property expression.</param>
+ public ColumnInfo AddMapping<T>(string columnName, Expression<Func<T, object>> propertyExpression)
+ {
+ var typeMapper = TypeMapperFactory.Create(typeof(T));
+ var prop = GetPropertyInfo(propertyExpression);
+
+ if (!typeMapper.ColumnsByName.ContainsKey(columnName))
+ typeMapper.ColumnsByName.Add(columnName, new List<ColumnInfo>());
+
+ var columnInfo = typeMapper.ColumnsByName[columnName].FirstOrDefault(ci => ci.Property.Name == prop.Name);
+ if (columnInfo is null)
+ {
+ columnInfo = new ColumnInfo(prop);
+ typeMapper.ColumnsByName[columnName].Add(columnInfo);
+ }
+
+ return columnInfo;
+ }
+
+ /// <summary>
+ /// Adds a mapping from a column index to a property.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="columnIndex">Index of the column.</param>
+ /// <param name="propertyExpression">The property expression.</param>
+ public ColumnInfo AddMapping<T>(int columnIndex, Expression<Func<T, object>> propertyExpression)
+ {
+ var typeMapper = TypeMapperFactory.Create(typeof(T));
+ var prop = GetPropertyInfo(propertyExpression);
+ var idx = columnIndex - 1;
+
+ if (!typeMapper.ColumnsByIndex.ContainsKey(idx))
+ typeMapper.ColumnsByIndex.Add(idx, new List<ColumnInfo>());
+
+ var columnInfo = typeMapper.ColumnsByIndex[idx].FirstOrDefault(ci => ci.Property.Name == prop.Name);
+ if (columnInfo is null)
+ {
+ columnInfo = new ColumnInfo(prop);
+ typeMapper.ColumnsByIndex[idx].Add(columnInfo);
+ }
+
+ return columnInfo;
+ }
+
+ /// <summary>
+ /// Adds a mapping from a column name to a property.
+ /// </summary>
+ /// <param name="t">The type that contains the property to map to.</param>
+ /// <param name="columnName">Name of the column.</param>
+ /// <param name="propertyName">Name of the property.</param>
+ public ColumnInfo AddMapping(Type t, string columnName, string propertyName)
+ {
+ var typeMapper = TypeMapperFactory.Create(t);
+ var prop = t.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
+
+ if (!typeMapper.ColumnsByName.ContainsKey(columnName))
+ typeMapper.ColumnsByName.Add(columnName, new List<ColumnInfo>());
+
+ var columnInfo = typeMapper.ColumnsByName[columnName].FirstOrDefault(ci => ci.Property.Name == prop.Name);
+ if (columnInfo is null)
+ {
+ columnInfo = new ColumnInfo(prop);
+ typeMapper.ColumnsByName[columnName].Add(columnInfo);
+ }
+
+ return columnInfo;
+ }
+
+ /// <summary>
+ /// Adds a mapping from a column name to a property.
+ /// </summary>
+ /// <param name="t">The type that contains the property to map to.</param>
+ /// <param name="columnIndex">Index of the column.</param>
+ /// <param name="propertyName">Name of the property.</param>
+ public ColumnInfo AddMapping(Type t, int columnIndex, string propertyName)
+ {
+ var typeMapper = TypeMapperFactory.Create(t);
+ var prop = t.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
+ var idx = columnIndex - 1;
+
+ if (!typeMapper.ColumnsByIndex.ContainsKey(idx))
+ typeMapper.ColumnsByIndex.Add(idx, new List<ColumnInfo>());
+
+ var columnInfo = typeMapper.ColumnsByIndex[idx].FirstOrDefault(ci => ci.Property.Name == prop.Name);
+ if (columnInfo is null)
+ {
+ columnInfo = new ColumnInfo(prop);
+ typeMapper.ColumnsByIndex[idx].Add(columnInfo);
+ }
+
+ return columnInfo;
+ }
+
+ /// <summary>
+ /// Ignores a property.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="propertyExpression">The property expression.</param>
+ public void Ignore<T>(Expression<Func<T, object>> propertyExpression)
+ {
+ var typeMapper = TypeMapperFactory.Create(typeof(T));
+ var prop = GetPropertyInfo(propertyExpression);
+
+ typeMapper.ColumnsByName.Where(c => c.Value.Any(cc => cc.Property.IsIdenticalTo(prop)))
+ .ToList().ForEach(kvp => typeMapper.ColumnsByName.Remove(kvp.Key));
+ }
+
+ /// <summary>
+ /// Ignores a property.
+ /// </summary>
+ /// <param name="t">The type that contains the property to map to.</param>
+ /// <param name="propertyName">Name of the property.</param>
+ public void Ignore(Type t, string propertyName)
+ {
+ var typeMapper = TypeMapperFactory.Create(t);
+ var prop = t.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
+
+ typeMapper.ColumnsByName.Where(c => c.Value.Any(cc => cc.Property.IsIdenticalTo(prop)))
+ .ToList().ForEach(kvp => typeMapper.ColumnsByName.Remove(kvp.Key));
+ }
+
+ /// <summary>
+ /// Sets a name normalization function.
+ /// This function is used when the <see cref="ExcelMapper"/> object tries to find a property name from a header cell value.
+ /// It can be used if the input header cell values may contain a larger number of possible values that can be easily mapped
+ /// backed to a single property name through a function, e.g. if the header cell may contain varying amounts of whitespace.
+ /// The default is the identity function.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="normalizeName">The name normalization function.</param>
+ public void NormalizeUsing<T>(Func<string, string> normalizeName)
+ {
+ var typeMapper = TypeMapperFactory.Create(typeof(T));
+ typeMapper.NormalizeName = normalizeName;
+ }
+
+ /// <summary>
+ /// Sets a name normalization function.
+ /// This function is used when the <see cref="ExcelMapper"/> object tries to find a property name from a header cell value.
+ /// It can be used if the input header cell values may contain a larger number of possible values that can be easily mapped
+ /// backed to a single property name through a function, e.g. if the header cell may contain varying amounts of whitespace.
+ /// The default is the identity function.
+ /// </summary>
+ /// <param name="t">The type that contains the property to map to.</param>
+ /// <param name="normalizeName">The name normalization function.</param>
+ public void NormalizeUsing(Type t, Func<string, string> normalizeName)
+ {
+ var typeMapper = TypeMapperFactory.Create(t);
+ typeMapper.NormalizeName = normalizeName;
+ }
+
+ /// <summary>
+ /// Sets a default name normalization function.
+ /// This function is used when the <see cref="ExcelMapper"/> object tries to find a property name from a header cell value.
+ /// It can be used if the input header cell values may contain a larger number of possible values that can be easily mapped
+ /// backed to a single property name through a function, e.g. if the header cell may contain varying amounts of whitespace.
+ /// This default normalization function works across types. If a normalization function is set for a specific type it takes
+ /// precedence over this default function.
+ /// The default is the identity function.
+ /// </summary>
+ /// <param name="normalizeName">The name normalization function.</param>
+ public void NormalizeUsing(Func<string, string> normalizeName)
+ {
+ NormalizeName = normalizeName;
+ }
+
+ internal static readonly Regex ColumnLetterRegex = new("^$?[A-Z]+$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+
+ /// <summary>
+ /// Converts Excel column letters to column indexes (e.g. "A" yields 1).
+ /// </summary>
+ /// <param name="letter">The Excel column letter.</param>
+ /// <returns>The column index.</returns>
+ public static int LetterToIndex(string letter)
+ {
+ if (letter == null || !ColumnLetterRegex.IsMatch(letter))
+ throw new ArgumentException($"Column letters out of range: {letter}", nameof(letter));
+ return CellReference.ConvertColStringToIndex(letter) + 1;
+ }
+
+ /// <summary>
+ /// Converts a column index to the corresponding Excel column letter or letters (e.g. 1 yields "A").
+ /// </summary>
+ /// <param name="index">The column index.</param>
+ /// <returns>The Excel column letter or letters.</returns>
+ public static string IndexToLetter(int index)
+ {
+ if (index < 1)
+ throw new ArgumentException($"Column index out of range: {index}", nameof(index));
+ return CellReference.ConvertNumToColString(index - 1);
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Exceptions/ExcelMapperConvertException.cs b/src/Business/Grand.Business.Common/ExcelMapper/Exceptions/ExcelMapperConvertException.cs
new file mode 100644
index 000000000..9bec85644
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Exceptions/ExcelMapperConvertException.cs
@@ -0,0 +1,126 @@
+using System;
+using System.Runtime.Serialization;
+
+namespace Ganss.Excel.Exceptions
+{
+ /// <summary>
+ /// Represents an error that occurs when conversion of a cell value to the mapped property type fails.
+ /// </summary>
+ [Serializable]
+ public class ExcelMapperConvertException : Exception
+ {
+ /// <summary>
+ /// Gets the original cell value.
+ /// </summary>
+ /// <value>
+ /// The original cell value.
+ /// </value>
+ public object CellValue { get; }
+
+ /// <summary>
+ /// Gets the type of the property that the cell is mapped to.
+ /// </summary>
+ /// <value>
+ /// The type of the property that the cell is mapped to.
+ /// </value>
+ public Type TargetType { get; }
+
+ /// <summary>
+ /// Gets the line number of the cell where the error occurred.
+ /// </summary>
+ /// <value>
+ /// The line number of the cell where the error occurred.
+ /// </value>
+ public int Line { get; }
+
+ /// <summary>
+ /// Gets the column number of the cell where the error occurred.
+ /// </summary>
+ /// <value>
+ /// The column number of the cell where the error occurred.
+ /// </value>
+ public int Column { get; }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapperConvertException"/> class.
+ /// </summary>
+ public ExcelMapperConvertException() { }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapperConvertException"/> class.
+ /// </summary>
+ /// <param name="message">The message the describes the error.</param>
+ public ExcelMapperConvertException(string message) : base(message) { }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapperConvertException"/> class.
+ /// </summary>
+ /// <param name="message">The message the describes the error.</param>
+ /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
+ public ExcelMapperConvertException(string message, Exception innerException) : base(message, innerException) { }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapperConvertException"/> class.
+ /// </summary>
+ /// <param name="cellValue">The value of the cell where the error occurred.</param>
+ /// <param name="targetType">The type of the property the cell is mapped to.</param>
+ /// <param name="line">The line number of the cell where the error occurred.</param>
+ /// <param name="column">The column number of the cell where the error occurred.</param>
+ public ExcelMapperConvertException(object cellValue, Type targetType, int line, int column) : base(FormatMessage(cellValue, targetType, line, column))
+ {
+ CellValue = cellValue;
+ TargetType = targetType;
+ Line = line;
+ Column = column;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapperConvertException"/> class.
+ /// </summary>
+ /// <param name="cellValue">The value of the cell where the error occurred.</param>
+ /// <param name="targetType">The type of the property the cell is mapped to.</param>
+ /// <param name="line">The line number of the cell where the error occurred.</param>
+ /// <param name="column">The column number of the cell where the error occurred.</param>
+ /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
+ public ExcelMapperConvertException(object cellValue, Type targetType, int line, int column, Exception innerException)
+ : this(FormatMessage(cellValue, targetType, line, column), innerException)
+ {
+ CellValue = cellValue;
+ TargetType = targetType;
+ Line = line;
+ Column = column;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExcelMapperConvertException"/> class with serialized data.
+ /// </summary>
+ /// <param name="info">The object that holds the serialized data.</param>
+ /// <param name="context">The contextual information about the source or destination.</param>
+ protected ExcelMapperConvertException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ Line = info.GetInt32("Line");
+ Column = info.GetInt32("Column");
+ }
+
+ /// <summary>
+ /// Sets the <see cref="SerializationInfo"/> with information about the exception.
+ /// </summary>
+ /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+
+ info.AddValue("Line", Line);
+ info.AddValue("Column", Column);
+
+ base.GetObjectData(info, context);
+ }
+
+ private static string FormatMessage(object cellValue, Type targetType, int line, int column)
+ => $"Unable to convert \"{(cellValue == null || string.IsNullOrWhiteSpace(cellValue.ToString()) ? "<EMPTY>" : cellValue)}\" from [L:{line}]:[C:{column}] to {targetType}.";
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/Extensions.cs b/src/Business/Grand.Business.Common/ExcelMapper/Extensions.cs
new file mode 100644
index 000000000..c19610304
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/Extensions.cs
@@ -0,0 +1,40 @@
+using NPOI.SS.UserModel;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Ganss.Excel
+{
+ static class Extensions
+ {
+ internal static IEnumerable<IRow> Rows(this ISheet sheet)
+ {
+ var e = sheet.GetRowEnumerator();
+ while (e.MoveNext())
+ yield return e.Current as IRow;
+ }
+
+ internal static bool IsIdenticalTo(this MemberInfo memberInfo, MemberInfo other)
+ {
+ if (memberInfo == null || other == null) return false;
+ return memberInfo.Equals(other) || memberInfo.MetadataToken == other.MetadataToken;
+ }
+
+ /// <summary>
+ /// convert to Nullable type
+ /// </summary>
+ /// <param name="type"></param>
+ /// <returns></returns>
+ internal static Type ConvertToNullableType(this Type type)
+ {
+ if (type.IsPrimitive || type.IsValueType)
+ {
+ return typeof(Nullable<>).MakeGenericType(type);
+ }
+ return type;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/ITypeMapperFactory.cs b/src/Business/Grand.Business.Common/ExcelMapper/ITypeMapperFactory.cs
new file mode 100644
index 000000000..49c522a48
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/ITypeMapperFactory.cs
@@ -0,0 +1,24 @@
+using System;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// A caching factory of <see cref="TypeMapper"/> objects.
+ /// </summary>
+ public interface ITypeMapperFactory
+ {
+ /// <summary>
+ /// Creates a <see cref="TypeMapper"/> for the specified type.
+ /// </summary>
+ /// <param name="type">The type to create a <see cref="TypeMapper"/> object for.</param>
+ /// <returns>A <see cref="TypeMapper"/> for the specified type.</returns>
+ TypeMapper Create(Type type);
+
+ /// <summary>
+ /// Creates a <see cref="TypeMapper"/> for the specified object.
+ /// </summary>
+ /// <param name="o">The object to create a <see cref="TypeMapper"/> object for.</param>
+ /// <returns>A <see cref="TypeMapper"/> for the specified object.</returns>
+ TypeMapper Create(object o);
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/ParsingErrorEventArgs.cs b/src/Business/Grand.Business.Common/ExcelMapper/ParsingErrorEventArgs.cs
new file mode 100644
index 000000000..315903ae4
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/ParsingErrorEventArgs.cs
@@ -0,0 +1,32 @@
+using Ganss.Excel.Exceptions;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// Provides data for the <see cref="ExcelMapper.ErrorParsingCell"/> event.
+ /// Event handler can allow parsing to continue by setting <see cref="CancelEventArgs.Cancel"/> to true,
+ /// cancelling the exception.
+ /// </summary>
+ public class ParsingErrorEventArgs : CancelEventArgs
+ {
+ /// <summary>
+ /// The error captured
+ /// </summary>
+ public ExcelMapperConvertException Error { get; private set; }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ParsingErrorEventArgs"/> class.
+ /// </summary>
+ /// <param name="error">The error captured.</param>
+ public ParsingErrorEventArgs(ExcelMapperConvertException error)
+ {
+ Error = error;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/TypeMapper.cs b/src/Business/Grand.Business.Common/ExcelMapper/TypeMapper.cs
new file mode 100644
index 000000000..dea34dc09
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/TypeMapper.cs
@@ -0,0 +1,271 @@
+using Ganss.Excel.Exceptions;
+using NPOI.SS.UserModel;
+using System;
+using System.Collections.Generic;
+using System.Dynamic;
+using System.Linq;
+using System.Reflection;
+using System.Text.RegularExpressions;
+
+namespace Ganss.Excel
+{
+
+ /// <summary>
+ /// Maps a <see cref="Type"/>'s properties to columns in an Excel sheet.
+ /// </summary>
+ public class TypeMapper
+ {
+ /// <summary>
+ /// Gets the type being mapped.
+ /// </summary>
+ public Type Type { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the columns by name.
+ /// </summary>
+ /// <value>
+ /// The dictionary of columns by name.
+ /// </value>
+ public Dictionary<string, List<ColumnInfo>> ColumnsByName { get; set; } = new Dictionary<string, List<ColumnInfo>>(StringComparer.OrdinalIgnoreCase);
+
+ /// <summary>
+ /// Gets or sets the columns by index.
+ /// </summary>
+ /// <value>
+ /// The dictionary of columns by index.
+ /// </value>
+ public Dictionary<int, List<ColumnInfo>> ColumnsByIndex { get; set; } = new Dictionary<int, List<ColumnInfo>>();
+
+ internal Func<string, string> NormalizeName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Before Mapping action.
+ /// </summary>
+ internal ActionInvoker BeforeMappingActionInvoker { get; set; }
+
+ /// <summary>
+ /// Gets or sets the After Mapping action.
+ /// </summary>
+ internal ActionInvoker AfterMappingActionInvoker { get; set; }
+
+ static readonly Regex OneTwoLetterRegex = new("^[A-Z]{1,2}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+
+ /// <summary>
+ /// Creates a <see cref="TypeMapper"/> object from the specified type.
+ /// </summary>
+ /// <param name="type">The type.</param>
+ /// <returns>A <see cref="TypeMapper"/> object.</returns>
+ public static TypeMapper Create(Type type)
+ {
+ var typeMapper = new TypeMapper { Type = type };
+ typeMapper.Analyze();
+ return typeMapper;
+ }
+
+ /// <summary>
+ /// Creates a <see cref="TypeMapper"/> object from a list of cells.
+ /// </summary>
+ /// <param name="columns">The cells.</param>
+ /// <param name="useContentAsName"><c>true</c> if the cell's contents should be used as the column name; otherwise, <c>false</c>.</param>
+ /// <returns>A <see cref="TypeMapper"/> object.</returns>
+ public static TypeMapper Create(IEnumerable<ICell> columns, bool useContentAsName = true)
+ {
+ var typeMapper = new TypeMapper();
+
+ foreach (var col in columns)
+ {
+ var index = col.ColumnIndex;
+ var name = useContentAsName ? col.ToString() : ExcelMapper.IndexToLetter(index + 1);
+ var columnInfo = new DynamicColumnInfo(index, name);
+
+ typeMapper.ColumnsByIndex.Add(index, new List<ColumnInfo> { columnInfo });
+
+ if (!typeMapper.ColumnsByName.TryGetValue(name, out var columnInfos))
+ typeMapper.ColumnsByName.Add(name, new List<ColumnInfo> { columnInfo });
+ else
+ columnInfos.Add(columnInfo);
+ }
+
+ return typeMapper;
+ }
+
+ /// <summary>
+ /// Creates a <see cref="TypeMapper"/> object from an <see cref="ExpandoObject"/> object.
+ /// </summary>
+ /// <param name="o">The <see cref="ExpandoObject"/> object.</param>
+ /// <returns>A <see cref="TypeMapper"/> object.</returns>
+ public static TypeMapper Create(ExpandoObject o)
+ {
+ var typeMapper = new TypeMapper();
+ var eo = (IDictionary<string, object>)o;
+ var l = o.ToList();
+
+ eo.TryGetValue(IndexMapPropertyName, out var map);
+ var oneTwoLetter = map == null && eo.Keys.Where(k => k != IndexMapPropertyName).All(k => OneTwoLetterRegex.IsMatch(k));
+
+ for (int i = 0; i < o.Count(); i++)
+ {
+ var prop = l[i];
+ var name = prop.Key;
+ var ix = i;
+
+ if (name != IndexMapPropertyName)
+ {
+ if (map is Dictionary<string, int> indexMap)
+ {
+ if (indexMap.TryGetValue(name, out var im))
+ ix = im;
+ }
+ else if (oneTwoLetter)
+ {
+ ix = ExcelMapper.LetterToIndex(name) - 1;
+ }
+
+ var columnInfo = new DynamicColumnInfo(prop.Key, prop.Value != null ? prop.Value.GetType().ConvertToNullableType() : typeof(string));
+
+ typeMapper.ColumnsByIndex.Add(ix, new List<ColumnInfo> { columnInfo });
+
+ if (!typeMapper.ColumnsByName.TryGetValue(name, out var columnInfos))
+ typeMapper.ColumnsByName.Add(name, new List<ColumnInfo> { columnInfo });
+ else
+ columnInfos.Add(columnInfo);
+ }
+ }
+
+ return typeMapper;
+ }
+
+ const string IndexMapPropertyName = "__indexes__";
+
+ /// <summary>
+ /// Creates an <see cref="ExpandoObject"/> object that includes type mapping information.
+ /// </summary>
+ /// <returns>An <see cref="ExpandoObject"/> object.</returns>
+ public ExpandoObject CreateExpando()
+ {
+ var eo = new ExpandoObject();
+ var expando = (IDictionary<string, object>)eo;
+ var map = ColumnsByName.ToDictionary(c => c.Key, c => ColumnsByIndex.First(ci => ci.Value.First() == c.Value.First()).Key);
+
+ expando[IndexMapPropertyName] = map;
+
+ return eo;
+ }
+
+ /// <summary>
+ /// Gets or sets the constructor to initialize the mapped type. Only used if the mapped type has no default constructor.
+ /// </summary>
+ public ConstructorInfo Constructor { get; set; }
+
+ /// <summary>
+ /// Gets or sets the constructor parameters by name.
+ /// </summary>
+ public Dictionary<string, ParameterInfo> ConstructorParams { get; set; }
+
+ void Analyze()
+ {
+ var props = Type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
+
+ foreach (var prop in props)
+ {
+ if (!(Attribute.GetCustomAttribute(prop, typeof(IgnoreAttribute)) is IgnoreAttribute))
+ {
+ var ci = new ColumnInfo(prop);
+
+ // make sure inherited attributes come before attributes defined on the type itself
+ // so the latter ones can overwrite the inherited ones in the dictionary below
+ // (see #192)
+ var selfAttribs = Attribute.GetCustomAttributes(prop, typeof(ColumnAttribute), inherit: false).Cast<ColumnAttribute>();
+ var inheritedAttribs = Attribute.GetCustomAttributes(prop, typeof(ColumnAttribute), inherit: true)
+ .Cast<ColumnAttribute>()
+ .Where(c => c.Inherit)
+ .Except(selfAttribs);
+ var attribs = inheritedAttribs.Concat(selfAttribs);
+
+ if (attribs.Any())
+ {
+ foreach (var columnAttribute in attribs)
+ {
+ ci = new ColumnInfo(prop);
+ if (!string.IsNullOrEmpty(columnAttribute.Name))
+ {
+ if (!ColumnsByName.ContainsKey(columnAttribute.Name))
+ ColumnsByName.Add(columnAttribute.Name, new List<ColumnInfo>());
+
+ ColumnsByName[columnAttribute.Name].Add(ci);
+ }
+ else if (!ColumnsByName.ContainsKey(prop.Name))
+ ColumnsByName.Add(prop.Name, new List<ColumnInfo>() { ci });
+
+ if (columnAttribute.Index > 0)
+ {
+ var idx = columnAttribute.Index - 1;
+ if (!ColumnsByIndex.ContainsKey(idx))
+ ColumnsByIndex.Add(idx, new List<ColumnInfo>());
+
+ ColumnsByIndex[idx].Add(ci);
+ }
+
+ ci.Directions = columnAttribute.Directions;
+ }
+ }
+ else if (!ColumnsByName.ContainsKey(prop.Name))
+ ColumnsByName.Add(prop.Name, new List<ColumnInfo>() { ci });
+
+ if (Attribute.GetCustomAttribute(prop, typeof(DataFormatAttribute)) is DataFormatAttribute dataFormatAttribute)
+ {
+ ci.BuiltinFormat = dataFormatAttribute.BuiltinFormat;
+ ci.CustomFormat = dataFormatAttribute.CustomFormat;
+ }
+
+ if (Attribute.GetCustomAttribute(prop, typeof(FormulaResultAttribute)) is FormulaResultAttribute)
+ ci.FormulaResult = true;
+
+ if (Attribute.GetCustomAttribute(prop, typeof(FormulaAttribute)) is FormulaAttribute)
+ ci.Formula = true;
+
+ if (Attribute.GetCustomAttribute(prop, typeof(JsonAttribute)) is JsonAttribute)
+ ci.Json = true;
+ }
+ }
+
+ var hasDefaultConstructor = Type.IsValueType || Type.GetConstructor(Type.EmptyTypes) != null;
+
+ if (!hasDefaultConstructor)
+ {
+ Constructor = Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
+ .OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
+
+ if (Constructor != null)
+ {
+ ConstructorParams = Constructor.GetParameters()
+ .Select((p, i) => (Param: p, Index: i, HasProp: props.Any(r => string.Equals(r.Name, p.Name, StringComparison.OrdinalIgnoreCase))))
+ .Where(p => p.HasProp)
+ .ToDictionary(p => p.Param.Name, p => p.Param, StringComparer.OrdinalIgnoreCase);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets the <see cref="ColumnInfo"/> for the specified column name.
+ /// </summary>
+ /// <param name="name">The column name.</param>
+ /// <returns>A <see cref="ColumnInfo"/> object or null if no <see cref="ColumnInfo"/> exists for the specified column name.</returns>
+ public List<ColumnInfo> GetColumnByName(string name)
+ {
+ ColumnsByName.TryGetValue(name, out List<ColumnInfo> col);
+ return col;
+ }
+
+ /// <summary>
+ /// Gets the <see cref="ColumnInfo"/> for the specified column index.
+ /// </summary>
+ /// <param name="index">The column index.</param>
+ /// <returns>A <see cref="ColumnInfo"/> object or null if no <see cref="ColumnInfo"/> exists for the specified column index.</returns>
+ public List<ColumnInfo> GetColumnByIndex(int index)
+ {
+ ColumnsByIndex.TryGetValue(index, out List<ColumnInfo> col);
+ return col;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/ExcelMapper/TypeMapperFactory.cs b/src/Business/Grand.Business.Common/ExcelMapper/TypeMapperFactory.cs
new file mode 100644
index 000000000..3df825593
--- /dev/null
+++ b/src/Business/Grand.Business.Common/ExcelMapper/TypeMapperFactory.cs
@@ -0,0 +1,43 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Dynamic;
+
+namespace Ganss.Excel
+{
+ /// <summary>
+ /// A caching factory of <see cref="TypeMapper"/> objects.
+ /// </summary>
+ public class TypeMapperFactory : ITypeMapperFactory
+ {
+ ConcurrentDictionary<Type, TypeMapper> TypeMappers { get; set; } = new ConcurrentDictionary<Type, TypeMapper>();
+
+ /// <summary>
+ /// Creates a <see cref="TypeMapper"/> for the specified type.
+ /// </summary>
+ /// <param name="type">The type to create a <see cref="TypeMapper"/> object for.</param>
+ /// <returns>A <see cref="TypeMapper"/> for the specified type.</returns>
+ public TypeMapper Create(Type type)
+ {
+ var typeMapper = TypeMappers.GetOrAdd(type, t => TypeMapper.Create(t));
+ return typeMapper;
+ }
+
+ /// <summary>
+ /// Creates a <see cref="TypeMapper"/> for the specified object.
+ /// </summary>
+ /// <param name="o">The object to create a <see cref="TypeMapper"/> object for.</param>
+ /// <returns>A <see cref="TypeMapper"/> for the specified object.</returns>
+ public TypeMapper Create(object o)
+ {
+ if (o is ExpandoObject eo)
+ {
+ return TypeMapper.Create(eo);
+ }
+ else
+ {
+ return Create(o.GetType());
+ }
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/Grand.Business.Common.csproj b/src/Business/Grand.Business.Common/Grand.Business.Common.csproj
index 25c0fdad8..24ed596cc 100644
--- a/src/Business/Grand.Business.Common/Grand.Business.Common.csproj
+++ b/src/Business/Grand.Business.Common/Grand.Business.Common.csproj
@@ -1,9 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\Build\Grand.Common.props" />
<ItemGroup>
- <PackageReference Include="ExcelMapper" Version="5.2.429" />
<PackageReference Include="HtmlRendererCore.PdfSharp" Version="1.0.5" />
- <PackageReference Include="NPOI" Version="2.5.6" />
+ <PackageReference Include="NPOI" Version="2.6.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\Grand.Domain\Grand.Domain.csproj" />
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
index 9b9d2fac8..d8947b897 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
@@ -24,7 +24,7 @@ namespace Grand.Business.Common.Services.ExportImport
{
WriteToXlsx(properties, worksheet, items, row++);
}
- xlPackage.Write(stream);
+ xlPackage.Write(stream, false);
return stream.ToArray();
}
}
@@ -52,7 +52,7 @@ namespace Grand.Business.Common.Services.ExportImport
}
public virtual byte[] BuilderExportToByte()
{
- xlPackage.Write(stream);
+ xlPackage.Write(stream, false);
return stream.ToArray();
}