softwareplay
softwareplay

Reputation: 1409

Guide how date cell is read by Apache poi

I'm importing an excel file with many rows. Some columns are dates and i have to read them as such but the format of the cell is not correctly read by Apache poi. Indeed the dates have to be dd/MM/YYYY but when i have 04/13/2017 the Apache poi library thinks it is in the format MM/dd/YYYY, and reads the date consequently.

How can i tell apache poi to read dates in the right format?

Below there is an example of my code:

                           case Cell.CELL_TYPE_NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    Date d = cell.getDateCellValue());
                                    System.out.println(myWorkBook.getSheetName(i) + "  " + cell.getNumericCellValue() + "\t");
}

Upvotes: 0

Views: 6657

Answers (1)

softwareplay
softwareplay

Reputation: 1409

The right way is using getDataFormatString as it is done in this answer Validating the excel date for MM/dd/yyyy format But the builtin formats are limited.

If the limitation of the built-in formats bothers you, casting the value as a string is done through Data formatter

DataFormatter formatter = new DataFormatter();
String formattedValue = formatter.formatCellValue(cell);

The validation of the date field is already performed from the Excel file, and the date is read as a string if it is not in the right format.

Upvotes: 1

Related Questions