使用POI从Excel工作表中获取日期

Mun*_*ian 0 java excel apache-poi

我使用以下代码使用POI从excel表中获取日期,

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

默认情况下,Excel工作表的日期格式为MM/dd/yy.但是如果我使月份值大于12(即> = 13),则格式将更改为dd/MM/yy.

通过上面的代码,如果我将日期定为10/11/2010,它将月份作为10,将日期作为11.如果我像15/10/2010那样给出,我将月份作为10,将日期作为15.

但我需要保持一种格式为dd/MM/yyyy.我怎样才能做到这一点?

ken*_*ohn 11

使用SimpleDateFormat格式化日期,因为"currentCell.getDateCellValue()"返回Date.

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

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

    } catch (ParseException e) {
            e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该可以防止正在发生的自动转换.