Wednesday, July 24, 2013

Reading and writing date value in excel with Apache POI

This post shows the code snippet on how to read and write java.util.Date object to an excel.
Writing date into excel is easy; 
Reading date value from excel we must make sure the cell type is date to avoid exception.

Reading date value from excel file

Cell cell = row.getCell(i);
Date dateValue = null;
if(cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
    if (DateUtil.isCellDateFormatted(cell)) {
        dateValue = cell.getDateCellValue();
    }
}


As long as the cell type defined as Date in the excel, regardless of any date format, we still managed to get back the date value as a java.util.Date object.
Then it can be used in java for any kind of operations.
example of different date format in excel

Writing date value to excel file

Cell cell = row.getCell(i);
if (cell == null)
    cell = row.createCell(i);
cell.setCellValue(new Date()); // current date time


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...