【问题标题】:Set Date format using Apache POI使用 Apache POI 设置日期格式
【发布时间】:2012-12-28 04:29:30
【问题描述】:

我想用 Apache POI 在 Excel 文件中以日期格式设置日期。该值将以这样的方式设置,以便在地址栏中显示为 mm/dd/YYYY,在单元格中显示为 dd-mmm(数字日期和月份缩写:01-Jan)。

【问题讨论】:

  • 请注意“地址栏”格式取决于您的区域设置,而不是 xls(x) 中的任何内容

标签: java date apache-poi


【解决方案1】:

您可以将CellStyle 应用于您需要填写的单元格。这是我过去工作中的一些代码sn-ps,它不完整但显示了基本思想:

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

【讨论】:

  • 谢谢@Gavin。这对我帮助很大。但我想从日期中删除时间戳。在这方面你能帮我吗?
  • “从日期中删除时间戳”是什么意思? @SaikatGupta
  • 嗨@Gavin:在excel单元格中日期应该显示为“30-JAN”,但如果我选择单元格,地址栏中的日期应该显示为“1/30/2013”​​而不是“1 /30/2013 12:01:00 AM”(没有时间戳)
  • 我将单元格值的日期格式改为“yyyy-MM-dd”,您可以根据自己的要求更改格式,格式字符串相当灵活。 @SaikatGupta
  • 我如何告诉它我想要它在 UTC 时区?描述我可以在“getFormat”方法中使用哪些字符的文档在哪里?
猜你喜欢
  • 2012-04-03
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多