Search code examples
c#excel-formulaepplusduration

epplus Excel Duration formula not working in C#


I have wrote the below code for duration calc in C#

ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
workSheet.View.RightToLeft = true;

var formula="MDURATION(43860.3507195718,44233,0.2,0.199014876362008,2,3)";

workSheet.Cells["Z8"].Formula = formula;
workSheet.Cells["Z8"].Calculate();
var result= (workSheet.Cells["Z8"].Value);

This formula works in Excel but does not work in this code Finally the value of the result variable becomes {#NAME?}. But its value in Excel is .803


Solution

  • As suggested in the comments current version of the epplus does not support the MDURATION function.

    However, you could use another NuGet Package: ExcelFinancialFunctions as follows:

    using Excel.FinancialFunctions;
    
    //...
    
    //var formula = "MDURATION(43860.3507195718,44233,0.2,0.199014876362008,2,3)";
    
    DateTime start = new DateTime(1900, 01, 01);
    double modifiedDuration = Financial.MDuration(
        start.AddDays(43860.3507195718), 
        start.AddDays(44233), 
        0.2, 
        0.199014876362008,
        (Frequency)2, 
        (DayCountBasis)3);
    
    workSheet.Cells["Z8"].Value = modifiedDuration;