Skip to content

Commit

Permalink
Limit quoting strings in excel to string that starts with one of form…
Browse files Browse the repository at this point in the history
…ula characters
  • Loading branch information
agrancaric committed Aug 19, 2024
1 parent d62c7ce commit dfe587a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ public class PoiExcelReportGenerator implements ExcelReportGenerator {

private static final Pattern TEMPLATE_VARIABLE_PATTERN = Pattern.compile("\\$\\{(.*?)}");

private static final List<String> FORMULA_CHARACTER_LIST = List.of("=", "+", "-", "@");

private final List<CellValueConverter> cellValueConverterList;

private final OutputStream outputStream;
Expand Down Expand Up @@ -149,8 +151,11 @@ private void setCellValue(Cell cell, Object value, CellStyle style) {
.orElse(null);

if (converter == null) {
cell.setCellValue(value.toString());
cell.getCellStyle().setQuotePrefixed(true);
String stringValue = value.toString();
cell.setCellValue(stringValue);
if (stringValue != null && FORMULA_CHARACTER_LIST.stream().anyMatch(stringValue::startsWith)) {
cell.getCellStyle().setQuotePrefixed(true);
}
}
else {
converter.setCellValue(cellHolder, value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,10 @@ void shouldExportDataToExcel() {
Instant now = Instant.now().truncatedTo(ChronoUnit.DAYS);
Object[] rowData = new Object[] {
1.1, "value", new Date(now.toEpochMilli()), ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS), OffsetDateTime.now().truncatedTo(ChronoUnit.DAYS), now, now, 1, 1.5F, (short) 1,
LocalDate.now(), LocalDateTime.now().truncatedTo(ChronoUnit.DAYS), BigDecimal.valueOf(1.5), 10L, TestEnum.FIRST, TestEnum.SECOND, null
LocalDate.now(), LocalDateTime.now().truncatedTo(ChronoUnit.DAYS), BigDecimal.valueOf(1.5), 10L, TestEnum.FIRST, TestEnum.SECOND, null, "=123"
};
// when resolving data from cells all dates are converted to instant, all decimal numbers are converted to double and all whole numbers are converted to integer
Object[] expectedRowData = new Object[] { 1.1, "value", now, now, now, now, now, 1, 1.5, 1, now, now, 1.5, 10, "First", "SECOND", null };
Object[] expectedRowData = new Object[] { 1.1, "value", now, now, now, now, now, 1, 1.5, 1, now, now, 1.5, 10, "First", "SECOND", null, "=123" };

// when
excelReportGenerator.writeRowData(rowData);
Expand Down

0 comments on commit dfe587a

Please sign in to comment.