如何设置date为typesdate在Excel中与Apache poi?

我正在使用apache poi 3.8创build一个excel文件。 这个excel文件需要包含一些date。

我正在试图用exceltypes“date”来格式化excel文件。 但我总是得到一个types的“自定义”。 我需要使用“date”types,所以它将根据用户设置进行本地化。

我已经尝试了以下内容:

Apache poidate格式

Apache POI本地化date到Excel单元格

但它不工作。

这是我有的代码:

XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("new sheet"); XSSFDataFormat df = wb.createDataFormat(); CellStyle cs = wb.createCellStyle(); cs.setDataFormat(df.getFormat("d-mmm-yy")); XSSFCell cell = sheet.createRow(0).createCell(0); Calendar c = Calendar.getInstance(); c.set(2012,3-1,18); cell.setCellValue( c.getTime() ); cell.setCellStyle(cs); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("c:\\temp\\dates-sworkbook.xlsx"); wb.write(fileOut); fileOut.close(); 

我应该使用哪种格式?

谢谢

date是特殊的内置格式之一。 如果你想明确地使用那个,那么你需要明确地select它。 (几乎Excel中使用的所有格式都是自定义格式,它们呈现的是如何指定的格式,但还有一些特殊格式)

在BuiltinFormats中 ,POI具有特殊的内置格式的完整列表(这比最近的Excel副本中的格式列表小得多)。 如果你确定你设置了其中的一个,而不是你自己的自定义格式string,它应该像你期望的那样运行

不知道你是否已经解决了这个问题,但是这里有一个解决这个问题的代码。 它实际上解决了我的问题。

 CreationHelper createHelper = wb.getCreationHelper(); ... cs.setDataFormat(createHelper.createDataFormat().getFormat("yourformat")); 

采取从http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

我明白你的问题。 我解决了使用Apache Poi的DateUtil。

 Cell cell = yourRow.createCell(yourIndex); cell.setCellValue(DateUtil.getExcelDate(yourDate); 

请享用 !!

它使用下面的解决scheme:

 DataFormatter fmt = new DataFormatter(); Object Excel1data=Excel.readExcel(Excel1, "Sheet3", rownumber, columnnumber1); String valueAsInExcel1 = fmt.formatCellValue((Cell) Excel1data); Object Excel2Data=Excel.readExcel(Excel2, "Sheet2", getrownumber, columnnmumber2); String valueAsInExcel2 = fmt.formatCellValue((Cell) Excel2Data); org.testng.Assert.assertEquals(valueAsInExcel1, valueAsInExcel2,"Incorrect data in RowNumber:"+getrownumber+" ColumnNumber:"+columnnmumber2); columnnumber1++;