【问题标题】:Using apache poi input Time使用 apache poi 输入时间
【发布时间】:2019-02-24 20:08:15
【问题描述】:

我已经使用Apahe POI将时间输入到excel文件中,如下所示

Time time = Time.valueOf("19:30:00");
CellStyle cellStyle1 = workbook.createCellStyle();
CreationHelper createHelper1 = workbook.getCreationHelper();
cellStyle1.setDataFormat(
        createHelper.createDataFormat().getFormat("HH:MM AM/PM"));
cell = row.getCell(1);
System.out.println(time.toString());
cell.setCellValue(time);
cell.setCellStyle(cellStyle1);

这导致了预期的excel但是发现了以下不匹配 excel的实际值和显示值不同-我怎样才能使它们相同,我是否使用不正确的方式更新Excel时间格式的值

【问题讨论】:

  • 你想在编辑栏看到什么?
  • 当我手动输入下午 7:30 的字段时,它会在公式栏中填充相同的内容
  • 您可以使用 Xcelite 写入 Excel,它将这些东西抽象出来 - 您只需创建一个 bean 类并在其上设置日期对象,然后它会序列化到 Excel:github.com/xcelite-io/xcelite

标签: java time format apache-poi


【解决方案1】:

Excel 中,日期和时间存储为浮点数,即自午夜 01/01/1900 以来的天数。

如果您存储的值小于1.0 - 它将被解释为时间,否则为日期,例如:

  1. 0.5 将等于 12:00:00
  2. 5.5 将等于 05.01.1900 12:00:00

要正确处理日期和时间,请使用org.apache.poi.ss.usermodel.DateUtil,例如您的示例可能如下所示:

    double time = DateUtil.convertTime("19:30:00");
    CellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setDataFormat(
            workbook.createDataFormat().getFormat("HH:MM AM/PM"));
    cell.setCellValue(time);
    cell.setCellStyle(cellStyle);

结果 Excel 会是这样:


假设问题是关于上述内容,Excel 中的实际日期/时间值应该是双精度值,并且表示值应该基于您设置的样式/模式;假设目标是实现这种相似性,即公式中的19:30:00 和单元格中的07:30 PM

如果不是,并且目标是在这两种情况下都有 07:30 PM - 那么您只需要存储一个字符串值,而不是日期/时间。

【讨论】:

  • 我试过 Date date123 = calendar.getTime();使用样式并且效果很好,感谢您的解释,我使用的是 Open Office,我想在不同的 Suits 中处理数据的方式不同
【解决方案2】:

我使用具有瑞典语言环境的 Office 365 ProPlus 中的 POI 3.17 和 Excel。我在您的代码中添加了几行(以创建工作簿和工作表等)。下面的代码工作正常。在单元格中,我得到“07:30 PM”和公式栏中的“1970-01-01 19:30:00”。如果你在运行我的代码(使用 POI 3.17)时没有得到类似的东西,我猜你的 Excel 有点奇怪。

public void createExcelFile() {
    XSSFWorkbook workbook = new XSSFWorkbook();
    Time time = Time.valueOf("19:30:00");
    CellStyle cellStyle1 = workbook.createCellStyle();
    CreationHelper createHelper1 = workbook.getCreationHelper();
    cellStyle1.setDataFormat(createHelper1.createDataFormat().getFormat("HH:MM AM/PM"));
    Sheet sheet = workbook.createSheet("Sheet");
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(1);
    System.out.println(time.toString());
    cell.setCellValue(time);
    cell.setCellStyle(cellStyle1);

    try {
        FileOutputStream outputStream = new FileOutputStream("C:/temp/file.xlsx");
        workbook.write(outputStream);
        workbook.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2017-10-14
    • 2010-10-17
    • 1970-01-01
    • 2022-06-13
    • 2013-02-06
    • 2015-04-10
    相关资源
    最近更新 更多