Search code examples
javaapache-poixssf

java POI XSSF FormulaEvaluator


I am having a problem when i save my new excel file. I want it that when it gets saved the formula calculates itself but at the moment it is just returning a string in the excel file. The formula is correct. I don't know exactly to get the FormulaEvaluator to work.

Here is where I enter my formula that returns a string:

dataRow1.createCell((short)5).setCellValue("=VLOOKUP(A"+rowCountVlookup+",'C:\\Users\\Admin\\Documents\\JCreator LE\\MyProjects\\WordCount\\classes\\[Pricing.xlsx]Sheet1'!$B$3:$E$41,4, FALSE)*E"+rowCountVlookup+"");

Any help would be much appreciated.


Solution

  • I use this code to evaluate a formula

    //I use an instance of the workbook for the Excel workbook I'm working at the moment
    Workbook wbook;
    
    private CellValue formulaEvaluation(Cell cell) {
        FormulaEvaluator formulaEval = wbook.getCreationHelper().createFormulaEvaluator();
        return formulaEval.evaluate(cell);
    }
    
    public Double obtieneObjetoNumericoCelda(Cell cell) {
        Double dblValue = null;
        if (cell != null) {
            switch(cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                dblValue = cell.getNumericCellValue();
                break;
            case Cell.CELL_TYPE_FORMULA:
                CellValue objCellValue = formulaEvaluation(cell);
                if (objCellValue.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                    dblValue = objCellValue.getNumberValue();
                }
                break;
            }
        }
        return dblValor;
    }