微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java - Apache POI - 仅在 MS Excel 中单元格的错误日期格式

如何解决Java - Apache POI - 仅在 MS Excel 中单元格的错误日期格式

这是我在网站上的第一篇文章,很抱歉,如果我错过了什么,我会尽量清楚

我正在通过 Apache POI 生成一个 XLSX 文件,其中一列包含日期(日期格式)

主要问题是包含日期的列在用 Microsoft Excel 打开时没有很好地转换为日期类型(在 LibreOffice for linux tho 中可以很好地查看)

In this image you can see how it is viewed from the LibreOffice

In this image you can see how it is in MS Office (any version)

这里是单元格格式和值的代码

private void setCellValue(Cell cell,Object value) {
    if (value instanceof String) {
        cell.setCellValue((String) value);
    } else if (value instanceof Integer) {
        cell.setCellValue((Integer) value);
    } else if (value instanceof Date) {
        cell.setCellValue((Date) value);

        CellStyle style = cell.getCellStyle();

        if (style == null) {
            style = getWorkbook().createCellStyle();
        }
        
        style.setDataFormat(getDateDataFormat());

        cell.setCellStyle(style);
    }
}

private short getDateDataFormat() {
    return getWorkbook()
            .getCreationHelper()
            .createDataFormat()
            .getFormat("m/d/yy");
}

在这个过程中使用了 XSSF 类型的工作簿,这里是生成工作簿的代码

public Reporte getReport(String titulo) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    getWorkbook().write(outputStream);
    getWorkbook().close();

    return new Reporte(titulo,new String(new Base64().encode(outputStream.toByteArray())));
}

(Reporte 类只有属性 Name 和 Content)

Curious thing: when I open the file with a text editor,it seems as it is a binary file and not a xml as it should be

奇怪的事情 2:当我将文件转换为 XML 然后用 MS Office 打开它时,它显示的日期是正确的

提前致谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。