首页 文章

在Excel中获取日期日期列的格式

提问于
浏览
0

我正在使用Apache POI 3.11版本来读取和编写Java中的excel文件

在我的输入excel文件中,我有一个包含日期的列 . 日期可以是任何格式,比如说dd / mm / yyyy hh:mm或yy / mm / dd等 . 在阅读文件时,我可以获得任何格式的日期 .

enter image description here

当我创建新的Excel文件作为输出时,我想写日期列 . 但我想使用输入excel文件中存在的相同日期格式 .

有没有办法,我可以通过它输出输入excel文件中的日期格式(上面的屏幕截图你可以看到日期是mm / dd / yyyy hh:mm:ss PM格式)

我不想使用 ***getCellStyle*** 函数,因为它返回完整的单元格样式,包括字体颜色,背景颜色等 . 我只想要输入excel文件中存在的单元格的日期格式信息 .

我正在尝试的方式:

CellStyle outputStyle = wb.createCellStyle();
Font textFont = wb.createFont();
 textFont.setFontName("Arial");
textFont.setFontHeightInPoints((short) 10);
textFont.setColor(IndexedColors.BLACK.getIndex());
.setFont(textFont);

 if (DateUtil.isCellDateFormatted(icell)) {
 outputStyle.setDataFormat(icell.getCellStyle().getDataFormat());
 ocell.setCellValue(icell.getDateCellValue());
 }

 ocell.setCellStyle(outputStyle);

它将单元格中的Date值写为数字 .

1 回答

  • 1

    您不必使用 getCellStyle 返回的整个CellStyle对象,只有getDataFormatStringCreationHelper的帮助下返回的单元格样式的数据格式字符串:

    // Create the cell style in the new WorkBook
    CreationHelper createHelper = outputWB.getCreationHelper();
    CellStyle outputStyle = outputWB.createCellStyle(); 
    
    // Set the data format using the data format string
    outputStyle.setDataFormat(createHelper.createDataFormat()
            .getFormat(cell.getCellStyle().getDataFormatString()));
    // Set the created cell style to the new cell
    newCell.setCellStyle(outputStyle);
    

    变量 cell 是从当前文件读取的 Cell ,变量 newCell 是要写入新文件的 Cell .

相关问题