我必须使用Java Apache POI库在Excel文件(.xlsx或.xls)中设置日期字段。

我尝试设置单元格的cellStyle和dataFormat,但是它没有将其设置为日期字段,而是将其存储为字符串或数字字段。

这是我的代码:

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


我想在excel中将字段设置为“ dd-MM-yyyy”格式,但可能未在DataFormat的Apache POI库BuiltinFormats中定义。

我在这里可能做错了,请提出建议。

最佳答案

Excel中的日期是数字,具有日期格式。因此,您需要相应地格式化单元格:

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

关于java - 如何使用Java Apache POI库在Excel中设置日期字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43319789/

10-13 04:58