Get String value, when I read from excel with Date type (apache poi)
45,184
Solution 1
You have 2 options:
- Use Java's
SimpleDateFormat
class to format the returnedDate
as aString
in the format of your choice. You can have aSimpleDateFormat
instance for each different format you need. - Use Apache POI's
DataFormatter
class to format the theCell
directly.
Solution 2
You can get the return value for cell#getDateCellValue() and use SimpleDateFormat to covert it to a String instance
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
// Get the date today using cell.getDateCellValue()
Date today = cell.getDateCellValue()
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String reportDate = df.format(today);
You can get the value of Date in String format - 31/10/2013. Hope this helps
Author by
Sergii Lisnychyi
Updated on August 11, 2020Comments
-
Sergii Lisnychyi almost 4 years
I have an xlsx file that I am reading with - Apache POI Library.
For example, In some row, I have such cells values:
01-Sep-13 | 15136.00| Matt|......
My goal is: Read all cells in the rows as String values. But as I see, I can't read 01-Sep-13 as string, it only represents like Date type () with cell.getDateCellValue();
1) Could I read somehow 01-Sep-13 as string: "01-Sep-13"; 2) Could I convert Date value to string in case I have different date patterns (ddMMyyyy) and (dd-MMM-yy);
Code:
When I iterate over rows and cells, Apache POI analyzes each cell type:
String normalizeCellType(Cell cell) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: return cell.getRichStringCellValue().getString()); case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); ???????????? System.out.println(date); } else { .... } break; case Cell.CELL_TYPE_BOOLEAN: return .... case Cell.CELL_TYPE_FORMULA: return .... default: System.out.println(); } }
-
Sergii Lisnychyi over 10 yearsThanks method a lot.In the class DateFormatter + .formatCellValue(cell) - returns string representation of cell