EPPlus
EPPlus copied to clipboard
Set format of columns in LoadFromCollection in runtime
When calling LoadFromCollection
it should be possible to set a format of columns in runtime. For example, it should be possible to set different formats depending on culture.
Overview (work in progress)
We introduce a new public interface in EPPlus: IExcelNumberFormatProvider
This interface has just one method: GetFormat(int numberFormatId)
which returns a string
(the number format).
Logic for providing different formats depending on custom logic in runtime can be implemented via this interface, see example below.
If the new property NumberFormatId
is set on the EPPlusTableColumnProperty
EPPlus will call the NumberFormatProvider and set the format it returns as number format of the entire column in the range.
public class MyNumberFormatProvider : IExcelNumberFormatProvider
{
public const int CurrencyFormat = 1;
string IExcelNumberFormatProvider.GetFormat(int numberFormatId)
{
switch(numberFormatId)
{
case CurrencyFormat:
return "#,##0.00\\ \"kr\"";
default:
return string.Empty;
}
}
}
As long as the implementing class has an empty constructor, formats can be set like this in LoadFromCollection
:
[EpplusTable(NumberFormatProviderType = typeof(MyNumberFormatProvider))]
public class NumberFormatWithTableAttribute
{
[EpplusTableColumn(Header = "First name")]
public string Name { get; set; }
[EpplusTableColumn(Header = "Salary", NumberFormatId = MyNumberFormatProvider.CurrencyFormat)]
public decimal Salary { get; set; }
}
If the implementing class needs constructor arguments it can be used like this:
_sheet.Cells["A1"].LoadFromCollection(items, o =>
{
o.PrintHeaders = true;
o.SetNumberFormatProvider(new MyNumberFormatProviderWithConstructorArgs(arg1, arg2));
});
To do
The OfficeOpenXml.LoadFunctions.IExcelNumberFormatProvider
should be moved to the EPPlus.Interfaces
library.