如何使用Java Apache POI将date格式从2016年5月4日转换为2016年4月5日
我读取.xlsx文件并检索date值,它应该input到文本框字段。
在Excel中,单元格的值是04/05/2016 。
但从单元格中获取date值时,值为2016年5月4日 。
如何将这个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,你可以做
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); }
您应该在文件区域中将date作为string。 我的读者喜欢这个。
switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: cellValue = String.valueOf((long) cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; }
然后你用SimpleDateFormatparsingstring。
我的格式化程序
public final static DateFormat BIRTHDAY_FORMATTER = new SimpleDateFormat("myPatterns");
和date;
Date date = BIRTHDAY_FORMATTER.parse(myCellValue);