Executing a formula in Excel via Apache-POI throws

2019-08-30 10:00发布

问题:

I am trying to learn Apache POI and how to execute formulas in Excel via Java.

I have a sample code, which should execute the following formula

IF(B1<5,IF(c1={"high mech","low mech","mid mech"},10,IF(c1="electronic",20,0)),IF(B1>=5,IF(c1={"electronic"},40,0),0))

Code:

    public class ExpressionExample {

        public static void main(String[] args) throws Exception {

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Sample sheet");
            Row row = sheet.createRow(0);
            FormulaEvaluator evaluator = workbook.getCreationHelper()
                    .createFormulaEvaluator();
            HSSFCell formulaCell = (HSSFCell) row.createCell(6);
            HSSFCell engineCC = (HSSFCell) row.createCell(1);
            HSSFCell Hydraulic = (HSSFCell) row.createCell(2);
            engineCC.setCellValue(5);
            Hydraulic.setCellValue("electronic");

            String line = "IF(B1<5,IF(c1={\"high mech\",\"low mech\",\"mid mech\"},10,IF(c1=\"electronic\",20,0)),IF(B1>=5,IF(c1={\"electronic\"},40,0),0))";
            System.out.println(line);
            formulaCell.setCellFormula(line);

            CellValue cellValue = evaluator.evaluate(formulaCell);
            System.out.println(BigDecimal.valueOf(cellValue.getNumberValue()).toPlainString());
        }
    }

However this throws a RuntimeException:

Exception in thread "main" java.lang.RuntimeException: Unexpected ptg class (org.apache.poi.ss.formula.ptg.ArrayPtg)
            at org.apache.poi.ss.formula.WorkbookEvaluator.getEvalForPtg(WorkbookEvaluator.java:683)
            at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateFormula(WorkbookEvaluator.java:527)
            at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288)
            at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:230)
            at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:354)
            at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluate(HSSFFormulaEvaluator.java:185)
        at ExpressionExample.main(ExpressionExample.java:30)

But when I run this same expresion in MS Excel:

IF(B1<5,IF(c1={"high mech","low mech","mid mech"},10,IF(c1="electronic",20,0)),IF(B1>=5,IF(c1={"electronic"},40,0),0))

I get the output as expected. Can anyone help me with this issue?