使用 POI 从 Excel 工作表获取日期
我使用 POI 使用以下代码从 Excel 工作表中获取日期,
if (DateUtil.isCellDateFormatted(currentCell))
{
Date date = currentCell.getDateCellValue();
cellValue = date.getDate() + "/" + (date.getMonth() + 1) + "/" + (1900 + date.getYear());
}
默认情况下 Excel 工作表的日期格式为 MM/dd/yy。但如果我使月份值大于 12(即 >= 13),则格式将更改为 dd/MM/yy。
通过上面的代码,如果我给日期为 10/11/2010,它给出月份为 10,日期为 11。如果我给它像 15/10/2010,我得到月份为 10,日期为 15。
但我需要保持一种格式,即 dd/MM/yyyy。我怎样才能实现这个目标?
I have get the date from excel sheet using POI using the below code,
if (DateUtil.isCellDateFormatted(currentCell))
{
Date date = currentCell.getDateCellValue();
cellValue = date.getDate() + "/" + (date.getMonth() + 1) + "/" + (1900 + date.getYear());
}
By default the date format of excel sheet is MM/dd/yy. But if I make the month value is greater than 12 (i.e >= 13), the format is changed to dd/MM/yy.
By the above code,If I give date as 10/11/2010, it gives month as 10 and date as 11. If I give it like 15/10/2010, I got month as 10 and date as 15.
But I need to maintain the one format that is dd/MM/yyyy. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 SimpleDateFormat 来格式化日期,因为“currentCell.getDateCellValue()) 返回一个日期。
这应该会阻止正在发生的自动转换。
Use SimpleDateFormat to format the date because "currentCell.getDateCellValue()) returns a Date.
This should prevent the automatic conversion that is taking place.
您可以尝试使用 org.apache.poi.ss.usermodel.DataFormatter - 假设您将 Excel 文件设置为将日期单元格格式设置为 dd/mm/yyyy,那么它应该能够从细胞。
或者,如果您的单元格格式为日期但格式不同,那么您有两种选择。一种是将单元格样式更改为 dd/mm/yyyy 格式,然后要求 DataFormatter 对其进行格式化,另一种是从 DateUtil 获取 java.util.Date 对象,然后按照其他人的建议使用 SimpleDateFormat 格式对其进行格式化。
You could maybe try using org.apache.poi.ss.usermodel.DataFormatter - assuming you'd set your Excel file up to format the date cell as dd/mm/yyyy, then it should be able to render it for you from the cell.
Alternately, if your cell is formatted as a date but in a different format, then you have two choices. One is to change the cell style to have a dd/mm/yyyy format and then ask DataFormatter to format it, the other is to get the java.util.Date object from DateUtil and then format it with a SimpleDateFormat format as others have suggested.
确保 Excel 中的字段本身配置为 Excel 中的 DATE 数据类型。那么 Excel 中的实际格式应该与 POI 如何读取它无关。
Ensure that the field in Excel itself is configured as a DATE datatype in Excel. Then the actual format in Excel should be irrelevant to how POI reads it.