简体   繁体   中英

How to set date field in excel using java apache poi library?

I have to set the date field in excel file (.xlsx or .xls) using java apache poi library.

I have tried setting the cellStyle and dataFormat of the cell but it does not set it as date field and instead stores it as string or numeric field.

Here is my code:

XSSFWorkBook wb = new XSSFWorkBook();
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-mm-yyyy")); // I have tried different formats here but none working
cell = row.createCell(1);
cell.setCellValue(new Date()); // does not store anything
//cell.setCellValue(new Date().getTime()); // stores the time in milliseconds
//cell.setCellValue(new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
cell.setCellStyle(cellStyle);

I want to set the field as "dd-MM-yyyy" format in excel but it might not be defined in Apache POI Library BuiltinFormats in DataFormat.

I may be doing something wrong here, please suggest.

Dates in Excel are numeric, with a date formatting. So you need to format your cell accordingly:

Date date = ...
cellStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("dd-mm-yyyy"));
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(date);
cell.setCellStyle(cellStyle);

you can try this approach

XSSFFont yourFont = (XSSFFont)workbook.CreateFont();
yourFont.FontHeightInPoints = (short)10;

XSSFCellStyle dateCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat dateDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
dateCellStyle.SetDataFormat(dateDataFormat.GetFormat(("dd-mm-yyyy"));
dateCellStyle.SetFont(yourFont);
sheet.SetDefaultColumnStyle(col, dateCellStyle);

Old question but as I've just had a similar case, I can tell you, that your code snippet here should work.

I guess that your problem lies outside your displayed code... Do you use an excel template with existing column format or something that could overwrite your CellStyle?

My working code with a german date format:

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

... application of style to each cell with a java.util.Date object:

cell.setCellValue(date);  //java.util.Date date
cell.setCellStyle(cellStyle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM