Apache POI和EasyExcel 第六集:Apache POI的Excel读取单元格中的计算公式
一、资源
- 代码实现中的带有计算公式的Excel(xls)
- 链接:https://pan.baidu.com/s/1-iOXn4ZnzM9eFcNbo40Gzg
提取码:0916
二、代码实现
@Test
public void testFormula() throws Exception {
InputStream is = new FileInputStream(path + "计算公式.xls");
HSSFWorkbook workbook = new HSSFWorkbook(is);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(4);
Cell cell = row.getCell(0);
FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(workbook);
int cellType = cell.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_FORMULA:
String formula = cell.getCellFormula();
System.out.println(formula);
CellValue evaluate = formulaEvaluator.evaluate(cell);
String cellValue = evaluate.formatAsString();
System.out.println(cellValue);
break;
case Cell.CELL_TYPE_STRING:
case Cell.CELL_TYPE_BLANK:
case Cell.CELL_TYPE_ERROR:
case Cell.CELL_TYPE_BOOLEAN:
case Cell.CELL_TYPE_NUMERIC:
break;
}
}