Apache poi日期格式

Lal*_*tar 15 java apache-poi

嗨我正在阅读csv文件,并在01-01-2011获取日期,但我希望它以2011年1月1日格式,当我使用apache poi库编写.xlsx文件.我的代码是

XSSFDataFormat df = workBook.createDataFormat();
cs.setDataFormat(df.getFormat("dd-MMM-yy"));
Run Code Online (Sandbox Code Playgroud)

但它不适合我.我在哪里做错了.

Gag*_*arr 23

您不仅需要创建单元格格式,还需要将其应用于单元格!

XSSFDataFormat df = workBook.createDataFormat();
cs.setDataFormat(df.getFormat("d-mmm-yy"));

// Get / Create our cell
XSSFRow row = sheet.createRow(2);
XSSFCell cell = row.createCell(3);

// Set it to be a date
Calendar c = Calendar.getInstance();
c.set(2012,3-1,18); // Don't forget months are 0 based on Calendar
cell.setCellValue( c.getTime() );

// Style it as a date
cell.setCellStyle(cs);
Run Code Online (Sandbox Code Playgroud)

其次,您需要注意Java和Excel在表达日期格式规则方面略有不同.您应该打开Excel的副本,根据需要格式化样本单元格,然后记下所需的格式规则.在你的情况下,你选择了Java风格的大写字母M,而在Excel中它是小写的(见上文)

  • 您应该使用 org.apache.poi.ss.util.DateFormatConverter 通过调用 DateFormatConverter.convert(Locale.getDefault(), "d-MMM-yy") 将 Java 风格的格式化程序转换为 Excel 风格的格式化程序:https: //poi.apache.org/apidocs/dev/org/apache/poi/ss/util/DateFormatConverter.html (2认同)