如何使用Java Apache POI库在Excel中设置日期字段?
我必须使用Java apache poi库在Excel文件(.xlsx或.xls)中设置日期字段.
I have to set the date field in excel file (.xlsx or .xls) using java apache poi library.
我尝试设置单元格的cellStyle和dataFormat,但是它没有将其设置为日期字段,而是将其存储为字符串或数字字段.
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.
这是我的代码:
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中定义.
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.
Excel中的日期是数字,带有日期格式.因此,您需要相应地格式化单元格:
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);