Apache POI to Create Excel Date Time Cell in m/d/yy h:mm:ss Format

Tags: Apache POI

Java Code Examples for

  • org.apache.poi.ss.usermodel.Cell.createCell()

The example below to create a new Excel file with one worksheet and a date time cell in m/d/yy h:mm:ss format using Apache POI library.

package simplesolution.dev;

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.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

public class CreateHelperCreateDataFormatDateTimeExample {

    public static void main(String... args) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Simple Solution");
        Row row = sheet.createRow(0);

        CreationHelper creationHelper = workbook.getCreationHelper();
        CellStyle cellStyle = workbook.createCellStyle();
        short dateTimeFormat = creationHelper.createDataFormat().getFormat("m/d/yy h:mm:ss");
        cellStyle.setDataFormat(dateTimeFormat);
        Cell cell = row.createCell(0);
        cell.setCellValue(new Date());
        cell.setCellStyle(cellStyle);

        String fileName = "D:\\Data\\sample.xlsx";
        try(OutputStream outputStream = new FileOutputStream(fileName)) {
            workbook.write(outputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

The output Excel file as below:

Apache POI to Create Excel Date Time Cell

Happy Coding 😊

Writing Excel File Using Apache POI Library in Java

Apache POI to Create Excel Text Cell

Apache POI Create new Excel sheet

Java Create Excel File .xlsx using Apache POI

Java Read Excel File using Apache POI

Java Read Excel Workbook from File using Apache POI

Java Read Excel Workbook from InputStream using Apache POI

Java Read Password Protected Excel File using Apache POI

Java How to Iterate over Sheets Rows and Cells of Excel file using Apache POI

Java Add Rows to Existing Excel File using Apache POI

Java Add Sheet to Existing Excel File using Apache POI

Java Remove Sheet from Existing Excel File using Apache POI

Java Create Formula Excel Cells using Apache POI