通过Apache-POI在Excel中执行公式会抛出RuntimeException

时间:2015-05-21 07:08:02

标签: java excel apache-poi

我正在尝试学习Apache POI以及如何通过Java在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))

代码:

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

然而,这会引发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)

但是当我在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))

我按预期获得输出。任何人都可以帮我解决这个问题吗?

0 个答案:

没有答案