java POI XSSF FormulaEvaluator

我与影子孤独终老i 提交于 2019-12-08 01:52:54

问题


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.


回答1:


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;
}



回答2:


I managed to solve it in the end.

String strFormula = "ROUND((VLOOKUP(A"+rowCountVlookup+",'C:\\Users\\Admin\\Desktop\\[pricing.xlsx]Sheet1'!$B$3:$E$41,4, FALSE)*E"+rowCountVlookup+"),2)";
                            dataRow1.createCell((short)5).setCellType(Cell.CELL_TYPE_FORMULA);
                            dataRow1.createCell((short)5).setCellFormula(strFormula);


来源:https://stackoverflow.com/questions/10915475/java-poi-xssf-formulaevaluator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!