apache poi DataFormatter on cell containing date

2019-02-21 03:31发布

问题:

Good day.

I needed to get cell data from excel files as they look like and bumped to DataFormatter class of apache poi. This works like a charm except for cells containing date. Below is my code:

while (rowIterator.hasNext())
{
    Row row = rowIterator.next();

    StringBuilder rowDataBuilder = new StringBuilder();
    int iCellCount = row.getLastCellNum();
    for (int i = 0; i < iCellCount; i++)
    {
        Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
        rowDataBuilder.append(dataFormatter.formatCellValue(cell));
        rowDataBuilder.append(" | ");
    }

    _LOG.info("-----> row data: " + rowDataBuilder.toString());
}

For example a cell contains 5/3/2013, I only get 5/3/13. Would there be any solutions for this? Thanks.

回答1:

For fetching the date in desired format you can use following:

  SimpleDateFormat DtFormat = new SimpleDateFormat("dd/MM/yyyy");
  Date date=Test.getRow(RowNum).getCell(CellNum).getDateCellValue();
  System.out.println(DtFormat.format(date).toString());

And now if the cell value is 05/03/2013, it will give o/p as 05/03/2013. I hope this will resolve your problem.