如何使用java apache poi库在excel中设置日期字段?
问题描述:
我必须使用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定义。
我可能在这里做错了,请建议。
答
你可以试试这个方法
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
答
日期在Excel中的数值,与日期格式。所以你需要相应地格式化你的单元格:
Date date = ...
cellStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("dd-mm-yyyy"));
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(date);
cell.setCellStyle(cellStyle);
你忘了保存文件后?只有你的代码段中没有保存代码... – Gagravarr
我没有使用代码保存文件 FileOutputStream fileOut = new FileOutputStream(“ooxml_dataFormat.xlsx”); wb.write(fileOut); fileOut.close(); wb.close(); – agrawalsp