使用 Apache POI 设置日期格式 [英] Set Date format using Apache POI
问题描述
我想在带有 Apache POI 的 Excel 文件中以日期格式设置日期.该值将以这样的方式设置,以便在地址栏中显示为 mm/dd/YYYY,在单元格中显示为 dd-mmm(数字日期和月份缩写:01-Jan).
I want to set date in date format in an Excel file with Apache POI. The value will set in such a manner so that in Address Bar it will show as mm/dd/YYYY and in cell it will show as dd-mmm (numeric day and month abbreviation: 01-Jan).
推荐答案
您可以对需要填充的单元格应用 CellStyle
.这是我过去工作中的一些代码片段,它不是完整的,但显示了基本思想:
You can apply a CellStyle
to the cell you need to fill. Here some code snippets from my past work, it's not intact but shows the basic idea:
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
More information about date format in JDK, you should read this: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
这篇关于使用 Apache POI 设置日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!