Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Limit quoting strings in excel to formulas #217

Merged
merged 1 commit into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading