Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading date values from excel cell using POI HSSF API

I'm using POI HSSF API for my excel manipulations in Java. I've a date value "8/1/2009" in one of my excel cell and while I try to read this value using HSSF API, it detects the cell type as Numeric and returns the 'Double' value of my date. See the sample code below:

cell = row.getCell(); // date in the cell '8/1/2009'
switch (cell.getCellType()) {

case HSSFCell.CELL_TYPE_STRING:
    cellValue = cell.getRichStringCellValue().getString();
    break;
case HSSFCell.CELL_TYPE_NUMERIC:
    cellValue = new Double(cell.getNumericCellValue()).toString();
    break;
default:
}

Cell.getCellType() returns NUMERIC_TYPE and thus this code converts the date to double! :(

Is there any way to read the date as it is in HSSF POI !?

like image 342
Veera Avatar asked May 14 '09 06:05

Veera


People also ask

How does Apache POI read date value in excel?

Try this code. Date date = row. getCell(0). getDateCellValue(); //Get Date cell.

How do I find cell type date in POI?

setREPO_DATE(row. getCell(16). getDateCellValue()); it works fine if cell is formatted as date in excel.

What can I use instead of HSSFDateUtil?

In the last version of POI lib HSSFDateUtil is deprecated, use DateUtil instead.


3 Answers

You could take a look at:

HSSFDateUtil.isCellDateFormatted()

See the POI Horrible Spreadsheet Format API for more details on HSSFDateUtil:

http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html

That also provides some helper methods for returning Excel getExcelDate() and Java dates getJavaDate(). You need to be somewhat wary of different date formats though...

like image 93
Jon Avatar answered Sep 24 '22 14:09

Jon


If you want to reference the date in the same format in as in the Excel file, you should use the CellDateFormatter. Sample code:

CellValue cValue = formulaEv.evaluate(cell);
double dv = cValue.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
    Date date = HSSFDateUtil.getJavaDate(dv);

    String dateFmt = cell.getCellStyle().getDataFormatString();
    /* strValue = new SimpleDateFormat(dateFmt).format(date); - won't work as 
    Java fmt differs from Excel fmt. If Excel date format is mm/dd/yyyy, Java 
    will always be 00 for date since "m" is minutes of the hour.*/

    strValue = new CellDateFormatter(dateFmt).format(date); 
    // takes care of idiosyncrasies of Excel
}
like image 45
Sayantam Avatar answered Sep 22 '22 14:09

Sayantam


Excel treats dates and times as numbers... Jon said it better, so I won't echo him here...

However, sample code for what you've put in the question is at http://poi.apache.org/spreadsheet/quick-guide.html#CellContents

like image 6
Stobor Avatar answered Sep 25 '22 14:09

Stobor