Skip to content

Commit

Permalink
Handle Excel formula parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
amanteaux committed Jan 20, 2018
1 parent e326482 commit ee618f5
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ public String asString() {
// POI sometimes returns null when a cell is empty...
return null;
}
if (excelCell.getCellTypeEnum() == CellType.NUMERIC) {
if (excelCell.getCellTypeEnum() == CellType.NUMERIC
|| excelCell.getCellTypeEnum() == CellType.FORMULA) {
excelCell.setCellType(CellType.STRING);
return emptyToNull(excelCell.getStringCellValue());
}
return emptyToNullTrimmed(excelCell.getRichStringCellValue().getString(), trimValue);
}
Expand Down Expand Up @@ -70,16 +70,17 @@ private<T> NumberValue<T> toNumber(Function<Double, T> cast, Function<String, T>
}

private<T> T tryGetValue(Function<Double, T> cast) {
if (excelCell != null && excelCell.getCellTypeEnum() == CellType.NUMERIC) {
return cast.apply(excelCell.getNumericCellValue());
if (excelCell != null) {
if (excelCell.getCellTypeEnum() == CellType.FORMULA) {
excelCell.setCellType(CellType.NUMERIC);
}
if(excelCell.getCellTypeEnum() == CellType.NUMERIC) {
return cast.apply(excelCell.getNumericCellValue());
}
}
return null;
}

private static String emptyToNull(String value) {
return "".equals(value) ? null : value;
}

private static String emptyToNullTrimmed(String value, boolean shouldTrim) {
return "".equals(value) ?
null
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/com/coreoz/windmill/WindmillTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,16 @@ public void import_should_not_return_null_cell_csv() {
checkInexistantCell("/import.csv");
}

@Test
public void should_parse_xlsx_with_formula_as_string() throws Exception {
assertThat(parseFormulaFile().cell(2).asString()).isEqualTo("3");
}

@Test
public void should_parse_xlsx_with_formula_as_integer() throws Exception {
assertThat(parseFormulaFile().cell(2).asInteger().value()).isEqualTo(3);
}

@Test
public void should_parse_xlsx_with_trimmed_values() {
List<Import> result = Parsers
Expand Down Expand Up @@ -220,6 +230,15 @@ private Import parsingFunction(Row row) {
);
}

private Row parseFormulaFile() {
return Parsers
.xlsx()
.trimValues()
.parse(loadFile("/formula.xlsx"))
.findAny()
.get();
};

private void checkInexistantCell(String fileName) {
Row firstRow = Windmill
.parse(loadFile(fileName))
Expand Down
Binary file added src/test/resources/formula.xlsx
Binary file not shown.

0 comments on commit ee618f5

Please sign in to comment.