Checking Date Value of Excel Cells

In this section, you will learn to check the date value contained in a excel cell using Apache POI.

Checking Date Value of Excel Cells

Checking Date Value of Excel Cells

In this section, you will learn to check the date value contained in a excel cell using Apache POI.

Date can have numeric values as well as text values(ex. 21-Mar-98). For using utility method, date should contain only numeric values. So you need to check it before using utility function on cells.

Given below the Excel content :

Given below the code :

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class XLDateCell {
public static void main(String[] args) throws Exception {
String filename = "xls/test.xls";

FileInputStream fis = null;
try {
fis = new FileInputStream(filename);

HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);

//
// Read a cell the first cell on the sheet.
//
HSSFCell cell = sheet.getRow(1).getCell(0);
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
System.out.println("Cell type for date data type is numeric.");
}

//
// Using HSSFDateUtil to check if a cell contains a date.
//
if (HSSFDateUtil.isCellDateFormatted(cell)) {
System.out.println("The cell contains a date value: "
+ cell.getDateCellValue());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
}
}

OUTPUT

Cell type for date data type is numeric.
The cell contains a date value: Thu Jun 30 00:00:00 IST 2011

Download Source Code