GerardDellemann commented on a change in pull request #234: MM-82 Detect Column
Types
URL: https://github.com/apache/metamodel/pull/234#discussion_r354293219
##########
File path: excel/src/main/java/org/apache/metamodel/excel/ExcelUtils.java
##########
@@ -281,6 +357,57 @@ private static String getFormulaCellValue(Workbook wb,
Cell cell) {
return cell.getCellFormula();
}
+ private static Object getFormulaCellValueAsObject(final Workbook wb, final
Cell cell) {
+ // first try with a cached/precalculated value
+ try {
+ return
getIntegerOrDoubleValueFromDouble(cell.getNumericCellValue());
+ } catch (final Exception e) {
+ if (logger.isInfoEnabled()) {
+ logger.info("Failed to fetch cached/precalculated formula
value of cell: " + cell, e);
+ }
+ }
+
+ // evaluate cell first, if possible
+ try {
+ if (logger.isInfoEnabled()) {
+ logger
+ .info("cell({},{}) is a formula. Attempting to evaluate: {}",
cell.getRowIndex(), cell
+ .getColumnIndex(), cell.getCellFormula());
+ }
+
+ final FormulaEvaluator evaluator =
wb.getCreationHelper().createFormulaEvaluator();
+
+ // calculates the formula and puts it's value back into the cell
+ final Cell evaluatedCell = evaluator.evaluateInCell(cell);
+
+ return getCellValueAsObject(wb, evaluatedCell);
+ } catch (final RuntimeException e) {
+ logger
+ .warn("Exception occurred while evaluating formula at position
({},{}): {}", cell.getRowIndex(),
+ cell.getColumnIndex(), e.getMessage());
+ // Some exceptions we simply log - result will be then be the
actual formula
+ if (e instanceof FormulaParseException) {
+ logger.error("Parse exception occurred while evaluating cell
formula: " + cell, e);
+ } else if (e instanceof IllegalArgumentException) {
+ logger.error("Illegal formula argument occurred while
evaluating cell formula: " + cell, e);
+ } else {
+ logger.error("Unexpected exception occurred while evaluating
cell formula: " + cell, e);
+ }
+ }
+
+ // last resort: return the string formula
+ return cell.getCellFormula();
+ }
+
+ private static Number getIntegerOrDoubleValueFromDouble(final double
value) {
Review comment:
done
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services