How to read Excel cell having Date with Apache POI? How to read Excel cell having Date with Apache POI? apache apache

How to read Excel cell having Date with Apache POI?


NOTE: HSSFDateUtil is deprecated

If you know which cell i.e. column position say 0 in each row is going to be a date, you can go for row.getCell(0).getDateCellValue() directly.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()

UPDATE: Here is an example - you can apply this in your switch case code above. I am checking and printing the Numeric as well as Date value. In this case the first column in my sheet has dates, hence I use row.getCell(0).

You can use the if (HSSFDateUtil.isCellDateFormatted .. code block directly in your switch case.

if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)    System.out.println ("Row No.: " + row.getRowNum ()+ " " +        row.getCell(0).getNumericCellValue());    if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {        System.out.println ("Row No.: " + row.getRowNum ()+ " " +             row.getCell(0).getDateCellValue());    }}

The output is

Row No.: 0 39281.0Row No.: 0 Wed Jul 18 00:00:00 IST 2007Row No.: 1 39491.0Row No.: 1 Wed Feb 13 00:00:00 IST 2008Row No.: 2 39311.0Row No.: 2 Fri Aug 17 00:00:00 IST 2007


Yes, I understood your problem.If is difficult to identify cell has Numeric or Data value.

If you want data in format that shows in Excel, you just need to format cell using DataFormatter class.

DataFormatter dataFormatter = new DataFormatter();String cellStringValue = dataFormatter.formatCellValue(row.getCell(0));System.out.println ("Is shows data as show in Excel file" + cellStringValue);  // Here it automcatically format data based on that cell format.// No need for extra efforts 


import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.CellType;import org.apache.poi.hssf.usermodel.HSSFDateUtil;Row row = sheet.getRow(0);Cell cell = row.getCell(0);if(cell.getCellTypeEnum() == CellType.NUMERIC||cell.getCellTypeEnum() == CellType.FORMULA)   {     String cellValue=String.valueOf(cell.getNumericCellValue());     if(HSSFDateUtil.isCellDateFormatted(cell))      {          DateFormat df = new SimpleDateFormat("MM/dd/yyyy");          Date date = cell.getDateCellValue();          cellValue = df.format(date);       }          System.out.println(cellValue);    }