【问题标题】:c# npoi excel How to get a cell's formula VALUE?c# npoi excel 如何获取单元格的公式VALUE?
【发布时间】:2019-08-19 15:33:51
【问题描述】:

我在这样的循环中对一些单元格设置了一个公式:

System.String fm = "IF(B2,J2=J1,FALSE)"
another.GetRow(0).CreateCell(28).SetCellFormula(fm); 

我一直想知道如何得到这个公式的结果(值)而不是复制整个公式。

MessageBox.Show(another.GetRow(0).GetCell(28).ToString);

显示值 IF(B2,J2=J1,FALSE)

如何才能得到结果(值)而不是公式?

【问题讨论】:

    标签: c# excel npoi


    【解决方案1】:
    HSSFFormulaEvaluator formula = new HSSFFormulaEvaluator(workBook);
    

    然后您可以使用此公式对 excel 文件中的所有单元格使用

    formula.EvaluateAll();
    

    或者你可以将它用于像这样的特定单元格

    var cell = sheet.GetRow(row).GetCell(column);
                string Res = "";
    if (cell != null)
                {
                    formula.EvaluateInCell(cell);
    
                    switch (cell.CellType)
                    {
                        case NPOI.SS.UserModel.CellType.Numeric:
                            Res = sheet.GetRow(row).GetCell(column).NumericCellValue.ToString();
                            break;
                        case NPOI.SS.UserModel.CellType.String:
                            Res = sheet.GetRow(row).GetCell(column).StringCellValue;
                            break;
                    }
                }
    

    【讨论】:

      【解决方案2】:

      尝试使用:

      another.GetRow(0).GetCell(28).NumericCellValue;
      

      您可以根据列类型使用多个不同的属性。

      【讨论】:

      • 不能工作,显示值为0,但在excel中显示为FALSE
      • 所以尝试使用 BooleanCellValue 属性
      【解决方案3】:

      使用“EvaluateAllFormulaCells(workbook)”方法将所有公式设置为excel文件后对其进行评估。看这个链接How to re-calculate a cell's formula?

      【讨论】:

        【解决方案4】:

        使用 StringCellValue 从单元格中获取公式不会读取的值

        MessageBox.Show(another.GetRow(0).GetCell(28).StringCellValue
        

        【讨论】:

          【解决方案5】:

          试试这个 https://poi.apache.org/spreadsheet/eval.html

          例子

          FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
          CellValue cellValue = evaluator.evaluate(cell);
          

          【讨论】:

            猜你喜欢
            • 2021-11-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-03-25
            • 2014-02-11
            • 1970-01-01
            相关资源
            最近更新 更多