2017-04-10 150 views
0

我必須使用java apache poi庫在Excel文件(.xlsx或.xls)中設置日期字段。如何使用java apache poi庫在excel中設置日期字段?

我曾嘗試設置單元格的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」 格式,但它可能不會在Apache的POI庫BuiltinFormats在DATAFORMAT定義。

我可能在這裏做錯了,請建議。

+0

你忘了保存文件後?只有你的代碼段中沒有保存代碼... – Gagravarr

+0

我沒有使用代碼保存文件 FileOutputStream fileOut = new FileOutputStream(「ooxml_dataFormat.xlsx」); wb.write(fileOut); fileOut.close(); wb.close(); – agrawalsp

回答

0

你可以試試這個方法

XSSFFont yourFont = (XSSFFont)workbook.CreateFont(); 
yourFont.FontHeightInPoints = (short)10; 

XSSFCellStyle dateCellStyle = (XSSFCellStyle)workbook.CreateCellStyle(); 
XSSFDataFormat dateDataFormat = (XSSFDataFormat)workbook.CreateDataFormat(); 
dateCellStyle.SetDataFormat(dateDataFormat.GetFormat(("dd-mm-yyyy")); 
dateCellStyle.SetFont(yourFont); 
sheet.SetDefaultColumnStyle(col, dateCellStyle); 
+0

此代碼看起來像ASP.Net,我正在尋找Java代碼。無論如何,我也嘗試過,但沒有奏效 – agrawalsp

1

日期在Excel中的數值,與日期格式。所以你需要相應地格式化你的單元格:

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