How to Create Date Cell in XLSX Using POI in Java

By Arvind Rai, 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
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us