gpt4 book ai didi

java - 获取Excel中日期列的日期格式

转载 作者:行者123 更新时间:2023-12-01 09:30:03 25 4
gpt4 key购买 nike

我正在使用 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);

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

最佳答案

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

// 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到新文件中。

关于java - 获取Excel中日期列的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39509778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com