From 247f3250c85faa0338bca159135c772c4aa4f4a2 Mon Sep 17 00:00:00 2001 From: Joan Pujol Date: Wed, 12 May 2021 10:51:48 +0200 Subject: [PATCH] Be tolerant to cell formatter problems --- .../tech/tablesaw/io/xlsx/XlsxReader.java | 35 +++++++++++++++---- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/excel/src/main/java/tech/tablesaw/io/xlsx/XlsxReader.java b/excel/src/main/java/tech/tablesaw/io/xlsx/XlsxReader.java index cff8e1f16..e39ed7204 100644 --- a/excel/src/main/java/tech/tablesaw/io/xlsx/XlsxReader.java +++ b/excel/src/main/java/tech/tablesaw/io/xlsx/XlsxReader.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; +import java.util.IllegalFormatException; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -46,6 +47,8 @@ import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import tech.tablesaw.api.ColumnType; import tech.tablesaw.api.DoubleColumn; import tech.tablesaw.api.LongColumn; @@ -57,7 +60,7 @@ @Immutable public class XlsxReader implements DataReader { - + private static final Logger logger = LoggerFactory.getLogger(XlsxReader.class); private static final XlsxReader INSTANCE = new XlsxReader(); static { @@ -377,10 +380,18 @@ private Column appendValue(Column column, Cell cell) { Column stringColumn = (Column) column; String dataFormatStyle = cell.getCellStyle().getDataFormatString(); String val; - if ("general".equalsIgnoreCase(dataFormatStyle)) { - val = new CellGeneralFormatter().format(cell.getNumericCellValue()); - } else { - val = new CellNumberFormatter(dataFormatStyle).format(cell.getNumericCellValue()); + try { + if ("general".equalsIgnoreCase(dataFormatStyle)) { + val = new CellGeneralFormatter().format(cell.getNumericCellValue()); + } else { + val = new CellNumberFormatter(dataFormatStyle).format(cell.getNumericCellValue()); + } + } catch (IllegalFormatException e) { + logger.warn( + "Error formatting cell value {} to string: {}. Ignoring it's value", + cell.getNumericCellValue(), + e.getMessage()); + val = null; } stringColumn.append(val); } @@ -395,8 +406,18 @@ private Column appendValue(Column column, Cell cell) { // If column has String type try to honor it and leave the value as an string as similar // as posible as seen in Excel Column stringColumn = (Column) column; - String val = new CellGeneralFormatter().format(cell.getBooleanCellValue()); - stringColumn.append(val); + try { + String val = new CellGeneralFormatter().format(cell.getBooleanCellValue()); + stringColumn.append(val); + } catch (IllegalFormatException e) { + logger.warn( + "Error formatting cell value {} at ({},{}) to string: {}. Ignoring it's value", + cell.getNumericCellValue(), + cell.getColumnIndex(), + cell.getRowIndex(), + e.getMessage()); + stringColumn.append((String) null); + } } default: break;