I'm creating a spreadsheet with EPPlus. I am trying to get a formula to calculate a sum of values with this code:
using (var totalOccurrencesCell = priceComplianceWorksheet.Cells[rowToPopulate, 2])
{
totalOccurrencesCell.Style.Font.Size = DATA_FONT_SIZE;
totalOccurrencesCell.Style.Numberformat.Format = NUMBER_FORMAT_THOUSANDS;
if (rowToPopulate <= SUMMARY_HEADING_ROW + 1)
{
totalOccurrencesCell.Value = "0";
}
else
{
//totalOccurrencesCell.Formula = string.Format("SUM(B5:B{0})", rowToPopulate - 1);
// TODO: Comment out or remove below after finding out why the above is not working
totalOccurrencesCell.Formula = "SUM(B5:B19)";
totalOccurrencesCell.Calculate();
}
}
What I would think is correct is being applied to that cell, as can be seen here, namely "=SUM(B5:B19)":
So why is "0" the result? The same is true for column C, and D is also catawamptuously chawed up for some reason, too.
This similar code does work elsewhere on the sheet:
using (var totalVarianceCell = priceComplianceWorksheet.Cells[rowToPopulate, DETAIL_TOTALVARIANCE_COL])
{
totalVarianceCell.Style.Font.Size = DATA_FONT_SIZE;
totalVarianceCell.Style.Numberformat.Format = NUMBER_FORMAT_CURRENCY;
totalVarianceCell.Formula = string.Format("SUM(J{0}:J{1})", _firstDetailDataRow, rowToPopulate - 1);
totalVarianceCell.Calculate();
}
It sums the value in the appropriate range of column J (10), and when clicking in the "sum" cell, it shows "=SUM(J23:J39)" as the value there.
Why would it work in one case, but fail in the others?
NOTE: I am populating the cells like so ("total" is an int):
totalOccurrencesCell.Value = total.ToString("N0", CultureInfo.CurrentCulture);
UPDATE
This is inelegant and a bit disappointing, but as of now, at least, I'm having to "brute force it" this way:
totalOccurrencesCell.Value = SumCellVals(2, 5, rowToPopulate - 1);
. . .
private string SumCellVals(int colNum, int firstRow, int lastRow)
{
double runningTotal = 0.0;
double currentVal;
for (int i = firstRow; i <= lastRow; i++)
{
using (var taterTotCell = priceComplianceWorksheet.Cells[i, colNum])
{
currentVal = Convert.ToDouble(taterTotCell.Value);
runningTotal = runningTotal + currentVal;
}
}
return runningTotal.ToString();
}