How do I check if a cell contains a date value?

The code below check if the first cell of an Excel file contains a date value. In Excel the cell type for date is returned as HSSFCell.CELL_TYPE_NUMERIC, to make sure if it contains a date we can use a utility method DateUtil.isCellDateFormatted(Cell cell), this method will check if the cell value is a valid date.

package org.kodejava.poi;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;

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

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

        try (FileInputStream 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(0).getCell(0);
            if (cell.getCellType() == CellType.NUMERIC) {
                System.out.println("Cell type for date data type is numeric.");
            }

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

The example result of the code snippet:

Cell type for date data type is numeric.
The cell contains a date value: Fri Oct 08 00:00:00 CST 2021

Maven Dependencies

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>

Maven Central

Wayan

5 Comments

  1. I have both numeric cells and date cells in my spreadsheet. When I read then using POI, all of them are identified as Date type. How can I differentiate between numeric values and date values?

    Reply
  2. case Cell.CELL_TYPE_NUMERIC:
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            return df.format(cell.getDateCellValue());
        } else {
            DecimalFormat df = new DecimalFormat("##.###############");
            return df.format(cell.getNumericCellValue());
        }
    
    Reply

Leave a Reply to Ramya MurugesanCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.