Java Apache poi 日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9756748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apache poi date format
提问by Lalit Chattar
Hi i am reading csv file and getting date in 01-01-2011 but i want it in 01-Jan-2011 format when i write .xlsx file using apache poi library. my code is
嗨,我正在读取 csv 文件并在 01-01-2011 中获取日期,但是当我使用 apache poi 库编写 .xlsx 文件时,我希望它采用 01-Jan-2011 格式。我的代码是
XSSFDataFormat df = workBook.createDataFormat();
cs.setDataFormat(df.getFormat("dd-MMM-yy"));
but it is not working for me. where am i doing mistake.
但它对我不起作用。我在哪里做错了。
采纳答案by Gagravarr
Not only do you need to create a cell format, but you also need to apply it to the cell!
您不仅需要创建单元格格式,还需要将其应用于单元格!
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);
Secondly, you need to be aware that Java and Excel differ slightly in how they express Date formatting rules. You should open up a copy of Excel, format a sample cell how you want, then take a note of the formatting rules needed. In your case, you'd gone for a Java style upper case M, while in Excel it's lower case (see above)
其次,您需要注意 Java 和 Excel 在表达日期格式规则的方式上略有不同。您应该打开一个 Excel 副本,按照您想要的方式设置示例单元格的格式,然后记下所需的格式设置规则。在你的情况下,你选择了 Java 风格的大写 M,而在 Excel 中它是小写(见上文)