9

I set a formula on some cells in a loop like this:

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

I always wondered how to get the result (value) of this formula and not copy the entire formula.

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

it displays value IF(B2,J2=J1,FALSE)

how can get the result (value), not the formula itself?

Caio Tsubake
  • 101
  • 3
  • 14
user7099027
  • 123
  • 1
  • 1
  • 7

6 Answers6

7
HSSFFormulaEvaluator formula = new HSSFFormulaEvaluator(workBook);

then you can use this formula for all cells in your excel file by using

formula.EvaluateAll();

or you can use it for specific cell like this

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;
                }
            }
ajd.nas
  • 354
  • 2
  • 12
4

Try to use:

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

You can use several different properties based on column type.

Przemysław Kleszcz
  • 536
  • 1
  • 7
  • 13
2

Use "EvaluateAllFormulaCells(workbook)" method to evaluate all formulas after setting it into excel file. see this link How to re-calculate a cell's formula?

kumar chandraketu
  • 2,232
  • 2
  • 20
  • 25
2

Use StringCellValue to get the value from cell your formula will not read

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

You can set the cell type to a string, it worked for me as its getting the calculated value:

ICell cell = sheet.GetRow(i).GetCell(1);
cell.SetCellType(NPOI.SS.UserModel.CellType.String);
var value  = sheet.GetRow(i).Cells[1].StringCellValue.ToString();
0

try this https://poi.apache.org/spreadsheet/eval.html

example

FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
CellValue cellValue = evaluator.evaluate(cell);
Muflix
  • 6,192
  • 17
  • 77
  • 153