get Date from Excel Sheet using POI

2019-04-17 07:05发布

问题:

I have get the date from excel sheet using POI using the below code,

if (DateUtil.isCellDateFormatted(currentCell))
                {
                    Date date = currentCell.getDateCellValue();
                    cellValue = date.getDate() + "/" + (date.getMonth() + 1) + "/" + (1900 + date.getYear());
}

By default the date format of excel sheet is MM/dd/yy. But if I make the month value is greater than 12 (i.e >= 13), the format is changed to dd/MM/yy.

By the above code,If I give date as 10/11/2010, it gives month as 10 and date as 11. If I give it like 15/10/2010, I got month as 10 and date as 15.

But I need to maintain the one format that is dd/MM/yyyy. How can I achieve this?

回答1:

Use SimpleDateFormat to format the date because "currentCell.getDateCellValue()) returns a Date.

if (DateUtil.isCellDateFormatted(currentCell))
{
   try {

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    cellValue =  = sdf.format(currentCell.getDateCellValue());

    } catch (ParseException e) {
            e.printStackTrace();
    }
}

This should prevent the automatic conversion that is taking place.



回答2:

You could maybe try using org.apache.poi.ss.usermodel.DataFormatter - assuming you'd set your Excel file up to format the date cell as dd/mm/yyyy, then it should be able to render it for you from the cell.

// Get a date formatter, and ensure it does dd/mm/yyyy format
DataFormatter formatter = new DataFormatter(Locale.UK);

// Find date cells
for(Row r : sheet) {
  for(Cell c: r) {
     if(DateUtil.isCellDateFormatted(c)) {
        String date = DataFormatter.formatCellValue(c);
        // date should be the same as shown in Excel
     }
  }
}

Alternately, if your cell is formatted as a date but in a different format, then you have two choices. One is to change the cell style to have a dd/mm/yyyy format and then ask DataFormatter to format it, the other is to get the java.util.Date object from DateUtil and then format it with a SimpleDateFormat format as others have suggested.



回答3:

Ensure that the field in Excel itself is configured as a DATE datatype in Excel. Then the actual format in Excel should be irrelevant to how POI reads it.