使用POI从Excel工作表中获取date
我使用下面的代码从使用POI的Excel工作表中获取date,
if (DateUtil.isCellDateFormatted(currentCell)) { Date date = currentCell.getDateCellValue(); cellValue = date.getDate() + "/" + (date.getMonth() + 1) + "/" + (1900 + date.getYear()); }
默认情况下,Excel工作表的date格式是MM / dd / yy。 但是,如果我使月份值大于12(即> = 13),格式将更改为dd / MM / yy。
通过上面的代码,如果我给date为2010年10月11日,它将月份设为10和date为11.如果我给它像15/10/2010,我得到月份为10date为15。
但是我需要保持一种格式是dd / MM / yyyy。 我怎样才能做到这一点?
使用SimpleDateFormat格式化date,因为“currentCell.getDateCellValue())返回一个date。
if (DateUtil.isCellDateFormatted(currentCell)) { try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); cellValue = = sdf.format(currentCell.getDateCellValue()); } catch (ParseException e) { e.printStackTrace(); } }
这应该防止发生的自动转换。
你也许可以尝试使用org.apache.poi.ss.usermodel.DataFormatter – 假设你将Excel文件设置为格式化date单元格为dd / mm / yyyy,那么它应该能够从细胞。
// Get a date formatter, and ensure it does dd/mm/yyyy format DataFormatter formatter = new DataFormatter(Locale.UK); // Find date cells for(Row r : sheet) { for(Cell c: r) { if(DateUtil.isCellDateFormatted(c)) { String date = DataFormatter.formatCellValue(c); // date should be the same as shown in Excel } } }
或者,如果您的单元格格式化为date,但格式不同,则有两种select。 一种是将单元格样式改为dd / mm / yyyy格式,然后要求DataFormatter格式化,另一种是从DateUtil中获取java.util.Date对象,然后使用SimpleDateFormat格式对其进行格式化。
确保Excel中的字段本身在Excel中被configuration为DATE数据types。 那么在Excel中的实际格式应该与POI如何读取它无关。
- POI颜色仅限于IndexedColors吗?
- 无法使用Java和Apache POI写入Excel文件
- Apache poi HSSFWorkbook将覆盖XLS模板中的样式
- 专注于Excel中的第一个单元格
- 如何使用Apache POI解锁Excel表格中的特定单元格
- 如何去通过Apache POI工作簿的工作表?
- NoClassDefFoundError:UnsupportedFileFormatException当使用Apache poi写入Excel文件
- POI – SXSSFWorkbook – Excel发现不可读的内容
- 使用StreamingOutput对象写入excel文件。 (java.lang.ClassCastException)