Apache poi date excel

I’m using Apache POI 3.6, I want to read an excel file which has a date like this 8/23/1991.

 switch (cell.getCellType()) {

   ...
   ...

   case HSSFCell.CELL_TYPE_NUMERIC:
     value = "NUMERIC value=" + cell.getNumericCellValue();
     break;

   ...

 }

But it takes the numeric value type and returns the value like this 33473.0.

I’ve tried to use Numeric Cell Type although with no luck.

dbltemp=row.getCell(c, Row.CREATE_NULL_AS_BLANK).getNumericCellValue();

if (c == 6 || c == 9) {
    strTemp= new String(dbltemp.toString().trim());

    long tempDate = Long.parseLong(strTemp);
    Date date = new Date(tempDate);

    strVal = date.toString();
}

How can I fix my problem?

Jack's user avatar

Jack

2,80311 gold badges50 silver badges64 bronze badges

asked Jun 30, 2010 at 10:58

Venkat's user avatar

1

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.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007

answered Jun 30, 2010 at 11:40

JoseK's user avatar

JoseKJoseK

31k14 gold badges104 silver badges131 bronze badges

11

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 

answered Feb 22, 2017 at 13:03

Chintan's user avatar

ChintanChintan

5451 gold badge9 silver badges24 bronze badges

1

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);
    }

answered Aug 25, 2020 at 6:30

Kiruthika Velusamy's user avatar

2

For reading date cells this method has proven to be robust so far:

private LocalDate readCellAsDate(final Row row, final int pos) {
    if (pos == -1) {
        return null;
    }
    final Cell cell = row.getCell(pos - 1);
    if (cell != null) {
        cell.setCellType(CellType.NUMERIC);
    } else {
        return null;
    }
    if (DateUtil.isCellDateFormatted(cell)) {
        try {
            return cell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } catch (final NullPointerException e) {
            logger.error(e.getMessage());
            return null;
        }
    }
    return null;
}

answered Jul 13, 2019 at 19:19

yglodt's user avatar

yglodtyglodt

13.5k14 gold badges89 silver badges125 bronze badges

You need the DateUtils: see this article for details.

Or, better yet, use Andy Khan’s JExcel instead of POI.

answered Jun 30, 2010 at 11:03

duffymo's user avatar

duffymoduffymo

304k44 gold badges368 silver badges558 bronze badges

4

Apache Poi has a DateUtil.isCellDateFormatted(XSSFCell) it works great.

Object objData = switch (cell.getCellType()){
   case NUMERIC ->{
      if(DateUtil.isCellDateFormatted(cell)){
         yield cell.getDateCellValue();
      }else{
         yield cell.getNumericCellValue();
      }
  } //The rest of the cellTypes need to be implemented.
}

objData can now be tested for Date or Double.

answered Aug 22, 2022 at 11:34

Brian Green's user avatar

You can use CellDateFormatter to fetch the Date in the same format as in excel cell. See the following code:

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

    String df = cell.getCellStyle().getDataFormatString();

    strValue = new CellDateFormatter(df).format(date); 
}

answered Jun 1, 2018 at 12:36

Abhishek Mishra's user avatar

If you know the cell number, then i would recommend using getDateCellValue() method
Here’s an example for the same that worked for me —
java.util.Date date = row.getCell().getDateCellValue();
System.out.println(date);

answered May 29, 2019 at 16:53

user1416932's user avatar

user1416932user1416932

2273 silver badges4 bronze badges

Try this code.

XSSFWorkbook workbook = new XSSFWorkbook(new File(result));
    XSSFSheet sheet = workbook.getSheetAt(0);

    // Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        // For each row, iterate through all the columns
        Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                if (cell.getNumericCellValue() != 0) {
                    //Get date
                    Date date = row.getCell(0).getDateCellValue();



                    //Get datetime
                    cell.getDateCellValue()


                    System.out.println(date.getTime());
                }
                break;
            }
        }
    }

Hope is help.

answered Mar 26, 2020 at 12:26

superup's user avatar

superupsuperup

1,64713 silver badges12 bronze badges

package com.kscodes.sampleproject;

import java.io.File;

import java.io.FileOutputStream;

import java.util.Date;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.CreationHelper;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcelUsingPOI {

public static void main(String[] args) {

// Create instance of the class and call the writeExcelFile()

WriteExcelUsingPOI writeExcelUsingPOI = new WriteExcelUsingPOI();

writeExcelUsingPOI

.writeExcelFile(«C:\kscodes\ExcelDateFormatTest.xlsx»);

}

public void writeExcelFile(String fileName) {

XSSFWorkbook workbook = null;

FileOutputStream fileOutputStream = null;

try {

fileOutputStream = new FileOutputStream(new File(fileName));

// Create a Workbook

workbook = new XSSFWorkbook();

// Create an Empty Sheet

XSSFSheet sheet = workbook.createSheet(«Date Formats»);

CreationHelper creationHelper = workbook.getCreationHelper();

Row row = sheet.createRow(1);

// Create Cell and set value as new Date()

Cell cell = row.createCell((short) 1);

cell.setCellValue(new Date());

// Create Another Cell and set todays date in dd-mmm-yyyy format

cell = row.createCell((short) 2);

cell.setCellValue(new Date());

CellStyle style1 = workbook.createCellStyle();

style1.setDataFormat(creationHelper.createDataFormat().getFormat(

«dd-mm-yyyy»));

cell.setCellStyle(style1);

// Create Another Cell and set todays date in mm/dd/yyyy hh:mm:ss

// format. Note that we have created a new CellStyle for this cell.

// This is not modify the existing CellStyle that was created for

// previous cell

cell = row.createCell((short) 3);

cell.setCellValue(new Date());

CellStyle style2 = workbook.createCellStyle();

style2.setDataFormat(creationHelper.createDataFormat().getFormat(

«mm/dd/yyyy hh:mm:ss»));

cell.setCellStyle(style2);

workbook.write(fileOutputStream);

System.out.println(«Excel File created and written !!!!»);

} catch (Exception e) {

System.out.println(«An Exception occured while writing Excel» + e);

} finally {

try {

if (fileOutputStream != null) {

fileOutputStream.close();

}

if (workbook != null) {

workbook.close();

}

} catch (Exception e) {

}

}

}

}

Introduction

In this example I will show you how to create date and put it in an excel file using Apache POI in Java language. I will show you how to build the project using both maven and gradle build tools. I will also show you how to create date using Java 8 or prior to Java 8 on java.util.Date and java.util.Calendar.

The Apache POI is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft’s OLE 2 Compound Document format (OLE2). You can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is the Java Excel solution (for Excel 97-2008).

Prerequisites

Java 8+, Apache POI – 4.1.1/5.2.2, Gradle 5.6, Maven – 3.6.1 – 3.8.5

Project Setup

Create a standalone maven project or gradle based project in your favorite IDE or tool. The name or artifact id of the project is apache-poi-excel-date.

If you are creating maven based project then you can use the below pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>apache-poi-excel-date</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>5.2.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
			</plugin>
		</plugins>
	</build>
</project>

If you are creating gradle based project then you can use below build.gradle script for creating date in excel file:

plugins {
    id 'java-library'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    jcenter()
}

dependencies {
    implementation 'org.apache.poi:poi-ooxml:4.1.1'
    //required only for jdk 9 or above
    implementation('com.fasterxml.jackson.core:jackson-databind:2.10.1')
}

Create Date in Excel File

Now I will create date in excel file using Apache POI in Java technology. I will put four different kind of date values in excel file – default date, java.util.Date, java.util.Calendar and Java 8’s LocalDate & LocalDateTime.

public class ExcelDate {

	public static void main(String[] args) {
		final String fileName = "excel-date.xlsx";// "excel-date.xls";
		createExcel(fileName);
	}

	public static void createExcel(final String fileName) {
		// get the file extension
		String ext = ".xlsx";
		if (fileName != null) {
			int len = fileName.trim().lastIndexOf(".");
			ext = fileName.trim().substring(len);
		}

		Workbook workbook = null;

		// based on file extension create Workbook object
		if (".xls".equalsIgnoreCase(ext)) {
			workbook = new HSSFWorkbook();
		} else if (".xlsx".equalsIgnoreCase(ext)) {
			workbook = new XSSFWorkbook();
		}

		// create Sheet object
		// sheet name must not exceed 31 characters
		// the name must not contain 0x0000, 0x0003, colon(:), backslash(),
		// asterisk(*), question mark(?), forward slash(/), opening square
		// bracket([), closing square bracket(])
		Sheet sheet = workbook.createSheet("my_sheet");

		// Create first row. Rows are 0 based.
		Row row = sheet.createRow((short) 0);

		// Create a cell
		// put a value in cell.
		// default Date
		row.createCell(0).setCellValue(new Date());

		// style Date
		CreationHelper createHelper = workbook.getCreationHelper();
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("MM/dd/yyyy hh:mm:ss"));

		Cell cell = row.createCell(1);
		cell.setCellValue(new Date());
		cell.setCellStyle(cellStyle);

		// set date as java.util.Calendar
		CellStyle cellStyle2 = workbook.createCellStyle();
		cellStyle2.setDataFormat(createHelper.createDataFormat().getFormat("MMM/dd/yyyy hh:mm:ss"));
		cell = row.createCell(2);
		cell.setCellValue(Calendar.getInstance());
		cell.setCellStyle(cellStyle2);

		// set date as Java 8
		CellStyle cellStyle3 = workbook.createCellStyle();
		cellStyle3.setDataFormat(createHelper.createDataFormat().getFormat("MMM/dd/yyyy hh:mm:ss"));
		cell = row.createCell(3);
		cell.setCellValue(LocalDateTime.now());
		cell.setCellStyle(cellStyle3);

		CellStyle cellStyle4 = workbook.createCellStyle();
		cellStyle4.setDataFormat(createHelper.createDataFormat().getFormat("MMM/dd/yyyy"));
		cell = row.createCell(4);
		cell.setCellValue(LocalDate.now());
		cell.setCellStyle(cellStyle4);

		FileOutputStream fileOut = null;
		try {
			fileOut = new FileOutputStream(fileName);
			workbook.write(fileOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

Testing Date Creation in Excel Sheet

Run the above class, you will get excel-date.xlsx or excel-date.xls file created under the project root directory. Open the file you will get the output in sheet “my_sheet”.

create date in excel file using apache poi in java

Source Code

Download

April 24, 2014

This page will illustrate how to create date cell in XLSX using POI API in java. POI is strong API and supports formatting XLSX cell as Date. We can format cell according to our date format. To achieve this task we need to use CellStyle and CreationHelper API. In our example we will format a cell as yyyy-dd-MM.

short dateFormat = createHelper.createDataFormat().getFormat("yyyy-dd-MM"); 

Get the instance of CreationHelper and CellStyle using XSSFWorkbook . Get the format and set it sell.

CellStyle cellStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
short dateFormat = createHelper.createDataFormat().getFormat("yyyy-dd-MM");
cellStyle.setDataFormat(dateFormat);

Finally we have CellStyle instance. To use it, create a row and a cell inside it, assign a date value and set the cell style.
Find the complete example.

DateCellDemo.java

package com.concretepage.poi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DateCellDemo {
	public static void main(String[] args) throws IOException {
	    Workbook workbook = new XSSFWorkbook();
	    Sheet sheet = workbook.createSheet("sheet1");
    
	    CellStyle cellStyle = workbook.createCellStyle();
	    CreationHelper createHelper = workbook.getCreationHelper();
	    short dateFormat = createHelper.createDataFormat().getFormat("yyyy-dd-MM");
	    cellStyle.setDataFormat(dateFormat);
	    
	    Row row = sheet.createRow(0);
	    Cell cell = row.createCell(0);
	    cell.setCellValue(Calendar.getInstance());
	    cell.setCellStyle(cellStyle);

	    FileOutputStream fos =new FileOutputStream(new File("D:/xlsx/cp.xlsx"));
	    workbook.write(fos);
	    fos.close();
	    System.out.println("Done");
	}
} 

Open the XLSX file and check the date. It will be there in yyyy-dd-MM format.

How to Create Date Cell in XLSX Using POI in Java

Formatting Dates Using Apache POI — Introduction

In this tutorial, let us examine how to use built in formatters available in Apache POI, to format your date cells in Excel to the pattern you want, in Java, with an example program. Formatting a cell to a specific date value, requires a style (HSSFCellStyle) to be attached to it. In the style, you can use the method setDataFormat method and specify the formatter you want to use. Let us see a step by step guide in POI to attach built in date formatters to XLS documents in this example.

createCellStyle — Specify Date Format

The first step is to create your workbook and add a worksheet. We have done this many times now. After this, you should use workbook.createCellStyle() method and define styles in your workbook. Later, we will attach a date pattern to these styles. Java code snippet for this step is provided below:

                
                HSSFWorkbook my_workbook = new HSSFWorkbook();
                HSSFSheet my_sheet = my_workbook.createSheet("Cell Date");              
                
                HSSFCellStyle my_style_0 = my_workbook.createCellStyle();
                HSSFCellStyle my_style_1 = my_workbook.createCellStyle();

setDataFormat — Attach Date formats to Style

In this step, we use HSSFDataFormat class to retrieve some built in date formats that is available in POI. This is done using getBuiltinFormat method. The value retrieved is then passed to setDataFormat method, which attaches a date format to the styles created in step — 1. We use two styles in this example. Refer below for a code sample:

                                        
                my_style_0.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
                my_style_1.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
                

Attach Cells with Date Formats

We will now create some data in the worksheet and attach the styles to it. We use «Row» and «Cell» objects to define data. As this is a date based cell, we use java.util.Calendar and java.util.GregorianCalendar to define a date and attach it to the cell. This step is the key as it defines the cell value and attaches the format we created earlier to the cell. A code snippet to do this is provided below:

                
                Calendar calendar = new GregorianCalendar();
                calendar.set(1982,Calendar.NOVEMBER,25);
                          
                Row row = my_sheet.createRow(0);                
                Cell cell = row.createCell(0);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_0); 
                row = my_sheet.createRow(1);            
                cell = row.createCell(1);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_1); 

Finally, we write the workbook to a file to see the formats we applied.

Date Format to Excel Cells — Apache POI — Complete Java Program Example

The full Java code that explains how to use built in formatters to format date cell data in a XLS workbook is provided below:

import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
public class FormatCellData {  
        public static void main(String[] args) throws Exception{
                
                HSSFWorkbook my_workbook = new HSSFWorkbook();
                HSSFSheet my_sheet = my_workbook.createSheet("Cell Date");              
                
                HSSFCellStyle my_style_0 = my_workbook.createCellStyle();
                HSSFCellStyle my_style_1 = my_workbook.createCellStyle();
                                        
                my_style_0.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
                my_style_1.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
                
                Calendar calendar = new GregorianCalendar();
                calendar.set(1982,Calendar.NOVEMBER,25);
                          
                Row row = my_sheet.createRow(0);                
                Cell cell = row.createCell(0);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_0); 
                row = my_sheet.createRow(1);            
                cell = row.createCell(1);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_1); 
                
                FileOutputStream out = new FileOutputStream(new File("C:\cell_date_format.xls"));
                my_workbook.write(out);
                out.close();
        }
}

A screenshot of the cell data produced in the output is provided below: (output cell highlighted in yellow, with the format provided against it)

Excel POI - Format Cell Date Example - Java Program - Output
Excel POI — Format Cell Date Example — Java Program — Output

That completes a quick tutorial to use built in date formatters in POI to format your date data in Excel. In the next article, we will see how to write a custom formatter, instead of using built in formatters.

Like this post? Please share to your friends:
  • Anything one word or two
  • Anything before the word but
  • Anything after the word but
  • Anyone who googles the word dreams will come across
  • Any зва to word