我读取了一个 .xlsx 文件并检索了一个日期值,它应该被输入到一个文本框字段中。
在 Excel 中,单元格值为 04/05/2016。
但是从单元格中获取日期值时,该值显示为 04-May-2016。
如何将此 04-May-2016 格式转换为 mm/dd/yyy。
代码:
public static String readExcel(String filePath,String fileName,String sheetName,int RowNumber,int ColNumber) throws Exception{
Object result = null;
try
{
sheet=getSheet(filePath, fileName, sheetName);
row=sheet.getRow(RowNumber);
if(row != null)
{
//System.out.println("Row is not empty");
cell= row.getCell(ColNumber);
if(cell!=null)
{
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:// numeric value in excel
if(DateUtil.isCellDateFormatted(cell)){
//DateUtil.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH);
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
result = formatter.format(cell);
System.out.println("Today : " + result);
}
else{
result = new BigDecimal(cell.getNumericCellValue()).toPlainString();
}
break;
case Cell.CELL_TYPE_STRING: // string value in excel
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN: // boolean value in excel
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK: // blank value in excel
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: // Error value in excel
result = cell.getErrorCellValue()+"";
break;
}
}
else
{
return null;
}
}
else
{
//System.out.println("Row is empty");
return null;
}
inputStream.close();
}
catch (Exception ex){
ex.printStackTrace();
}
return result.toString();
}
控制台:
java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at utility.ExcelUtility.readExcel(ExcelUtility.java:116)
指导我伸出援手。
最佳答案
要获取日期,你可以这样做
Date myDate = cell.getDateCellValue()
然后像您的示例一样使用 SimpleDateFormat :
if(DateUtil.isCellDateFormatted(cell)){
Date myDate = cell.getDateCellValue();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String result = formatter.format(myDate);
System.out.println("Today : " + result);
}
关于java - 如何使用 Java Apache POI 将日期格式从 04-May-2016 转换为 04/05/2016,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37021144/