Skip to content

Instantly share code, notes, and snippets.

@abel533
Created October 17, 2017 08:22
Show Gist options
  • Save abel533/5ff569e78a3ae75fdec24214ef424799 to your computer and use it in GitHub Desktop.
Save abel533/5ff569e78a3ae75fdec24214ef424799 to your computer and use it in GitHub Desktop.
Excel计算公式 #excel
//https://poi.apache.org/spreadsheet/eval.html
//Using FormulaEvaluator.evaluateFormulaCell(Cell cell)
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment