【问题标题】:Get format of Date for date column in Excel获取Excel中日期列的日期格式
【发布时间】:2023-03-09 20:10:01
【问题描述】:

我正在使用 Apache POI 3.11 版本在 Java 中读写 excel 文件

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

当我创建新的 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);

它正在将单元格中的日期值写为数字。

【问题讨论】:

    标签: java excel apache date apache-poi


    【解决方案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

    【讨论】:

    • 您是否将值写入Date?您能否在问题中至少包括您如何编写以及如何编写日期单元格?
    • 是的,我写的是日期类型的值.. CellStyle outputStyle = wb.createCellStyle();字体 textFont = wb.createFont(); textFont.setFontName("Arial"); textFont.setFontHeightInPoints((短) 10); textFont.setColor(IndexedColors.BLACK.getIndex()); .setFont(textFont); if (DateUtil.isCellDateFormatted(icell)) { outputStyle.setDataFormat(icell.getCellStyle().getDataFormat()); ocell.setCellValue(icell.getDateCellValue()); } ocell.setCellStyle(outputStyle);
    • 更新了相关代码。请看一下。如果我遗漏了什么,请告诉我。
    • 我已经为你更新了答案。我希望第二种方法也适用于您。
    • 非常感谢您的快速回复。第二种方法对我有用。我也想使用 JXL api 来实现同样的目标。至于带有 xls 扩展名的 excel 表,我使用的是 jxl 库。有什么帮助吗?
    猜你喜欢
    • 1970-01-01
    • 2013-03-17
    • 2015-08-22
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多