【发布时间】:2016-08-22 22:32:06
【问题描述】:
我正在使用 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”单元格时,它会显示“=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();
}
【问题讨论】:
-
B 列中的单元格是否可以填充文本而不是整数?如果我尝试对 Excel 中的一个数据列求和,并且该列被“格式化”为“文本”,我的 SUM(A1:A4) 返回 0,即使我的 4 个单元格填充了 numbers实际上被当作文本阅读。这可以解释为什么您需要
Convert.ToDouble(taterTotCell.Value)才能使其正常工作? -
我必须检查填充数据的方式与使用公式的其他情况之间是否有任何区别;不过,在我看来,SUM() 应该在必要时将值转换为数字值。我正在像这样填充单元格(“total”是一个 int):totalOccurrencesCell.Value = total.ToString("N0", CultureInfo.CurrentCulture);
-
我建议您在Excel中打开文件,看看数据列是否标记为文本?在我的 Excel 电子表格中,包含将被读取为文本的数字的单元格用“绿色角”标识,还有一个“!”选择单元格时出现的图标。
-
不,我都看不到 - 没有绿色角落,选择任何这些单元格时也没有感叹号。我想我会保留更新中显示的手动求和代码。不过,谢谢。
-
似乎计算设置为手动。你可以试试 =SUMPRODUCT(B5:B19*1)
标签: c# excel-formula sum epplus epplus-4