使用 Apache POI 设置日期格式

2022-09-03 06:16:39

我想在使用Apache POI的Excel文件中以日期格式设置日期。该值将以这种方式设置,以便在地址栏中显示为mm/dd/YYYY,在单元格中显示为dd-mmm(数字日和月缩写:01-Jan)。


答案 1

您可以将 应用 到需要填充的单元格。以下是我过去工作的一些代码片段,它不是完整的,但显示了基本思想:CellStyle

Row row = sheet.createRow(0);
Cell cell = row.createCell((short) 0);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);

SimpleDateFormat datetemp = new SimpleDateFormat("yyyy-MM-dd");
Date cellValue = datetemp.parse("1994-01-01 12:00");
cell.setCellValue(cellValue);

//binds the style you need to the cell.
CellStyle dateCellStyle = wb.createCellStyle();
short df = wb.createDataFormat().getFormat("dd-mmm");
dateCellStyle.setDataFormat(df);
cell.setCellStyle(dateCellStyle);
    

有关JDK中日期格式的更多信息,您应该阅读以下内容:http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html


答案 2