Search code examples
c#excelepplus

Cant invoke Calculate method from EPPlus using C#


I have a cell with a formula, that I need to invoke Calculate() method on, to get the result.

Somehow I cannet invoke the Calculate method on any cells in my sheet, what am I missing?

I am using EPPlus version 4.0.5.0. My code is as follows:

ws2.Cells[failedRow, failedColumn + 1].Formula = "SUM(B20:B" + (failedRow - 1) + ")";

And I need Calculate on that same cell. Any ideas?


Solution

  • Revising my answer based on @Stewart mentioning the Formula Calculations they added.

    I tried again and it DOES seem to work. So, Jesper, in you case, cell.Calculate() should do it for you. I tried this:

        public void Formula_Calc_Test()
        {
            var datatable = new DataTable("tblData");
            datatable.Columns.AddRange(new[] {new DataColumn("Col1", typeof (int)), new DataColumn("Col2", typeof (int))});
    
            for (var i = 0; i < 10; i++)
            {
                var row = datatable.NewRow();
                row[0] = i;
                row[1] = i * 10;
                datatable.Rows.Add(row);
            }
    
            using (var pck = new ExcelPackage())
            {
                var workbook = pck.Workbook;
                var worksheet = workbook.Worksheets.Add("Sheet1");
                var cells = worksheet.Cells;
    
                cells.LoadFromDataTable(datatable, true);
    
                var failedRow = 11;
                cells["C1"].Formula = "SUM(B2:B" + (failedRow - 1) + ")";
                cells["C1"].Calculate();
                Console.WriteLine(cells["C1"].Value);
    
            }
        }
    

    And did get 360 in the output.