我正在用 EPPlus 创建一个电子表格。我正在尝试使用以下代码获取一个公式来计算值的总和:
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();
}
}
我认为正确的是应用于该单元格,如此处所示,即“=SUM(B5:B19)”:
那么为什么结果是“0”呢?C列也是如此,D也由于某种原因被猛烈地吞噬了。
这个类似的代码在工作表的其他地方确实有效:
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();
}
它对列 J (10) 的适当范围内的值求和,当单击“求和”单元格时,它显示“=SUM(J23:J39)”作为那里的值。
为什么它在一种情况下有效,但在其他情况下却失败了?
注意:我正在像这样填充单元格(“total”是一个 int):
totalOccurrencesCell.Value = total.ToString("N0", CultureInfo.CurrentCulture);
更新
这是不雅的,有点令人失望,但至少到目前为止,我不得不以这种方式“暴力破解”:
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();
}