Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EPPlus calculation not working

Tags:

c#

epplus

I am using c# and EPPlus to calculate bunch of sums. I am trying to apply a formula to a row as well as bunch of individual cells. However, my current way is not calculating the formula. When I use the value method it just posts the value as string and doesn't calculate either.

//=SUM(E123+G123+H123+I123) -F123
//=SUMIFS($P$4:$P$1000,$C$4:$C$1000,Q2,$A$4:$A$1000, $R2)

string formula = "= 2 *2";
            //double f = double.Parse(formula);
       // ws.Cells["q4"].Value = formula;
       ws.Cells["q4"].Formula =formula;
        ws.Cells["q4"].Style.Numberformat.Format = "#,##0";
        ws.Workbook.CalcMode = ExcelCalcMode.Automatic;
        ws.Cells["q4"].Calculate();


        if (ws.Cells["q4"].Value.ToString() != null)
        {
            string test = ws.Cells["q4"].Value.ToString();
            MessageBox.Show("the value :" + test);
        }
        else
        {
            MessageBox.Show("not working" );
        }
like image 902
MJC Avatar asked Dec 13 '25 02:12

MJC


1 Answers

I checked out the sample you gave with the formula of 2 * 2. It seems with EPPLus that:

string formula = "= 2 *2";

Must actually be:

string formula = "2 *2";

i.e without the equals sign. See my modification to your example below:

//  Just setting up a dummy package here so I can test your example
var pckg = new ExcelPackage();
pckg.Workbook.Worksheets.Add("Test");
var ws = pckg.Workbook.Worksheets.First(w => w.Name == "Test");

//  Now that I have a dummy worksheet, I run your code.
string formula = "2 *2"; //  Note I dropped the equal sign here from your original example
ws.Cells["q4"].Formula = formula;
ws.Cells["q4"].Style.Numberformat.Format = "#,##0";
ws.Workbook.CalcMode = ExcelCalcMode.Automatic;
ws.Cells["q4"].Calculate();

if (ws.Cells["q4"].Value.ToString() != null)
{
    string test = ws.Cells["q4"].Value.ToString();
    MessageBox.Show("the value :" + test); //  test = 4
}
else
{
    MessageBox.Show("not working" );
}

But I would think from the EPPLus documentation that you shouldn't have to worry about the equals sign if there is a formula in the cell of your loaded worksheet.

like image 149
Jacob Shanley Avatar answered Dec 15 '25 17:12

Jacob Shanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!