dhatim / fastexcel

Generate and read big Excel files quickly
Other
675 stars 122 forks source link

Cell.asDate() off by one error #140

Closed jameskennard closed 1 year ago

jameskennard commented 3 years ago

Hi,

I think I have found an off by one error when using Cell.asDate(). The test below creates a Workbook with one sheet, and sets one cell to a LocalDateTime of 1st Jan 1900. It then reads the workbook back in and asserts that the value in the cell is the 1st Jan 1900. The test fails because the date is read back in as 2nd Jan 1900.

@Test
public void shouldGetCellAsDate() throws IOException {
    // Given
    LocalDateTime writtenLocalDateTime = LocalDateTime.of(1900, Month.JANUARY, 1, 0, 0);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Workbook workbook = new Workbook(outputStream, "App", "1.0");
    Worksheet sheet = workbook.newWorksheet("sheet");
    sheet.value(0, 0, writtenLocalDateTime);
    sheet.style(0, 0).format("YYYY-MM-DD HH:SS").set();
    workbook.finish();

    ReadableWorkbook readableWorkbook = new ReadableWorkbook(new ByteArrayInputStream(outputStream.toByteArray()));
    Cell cell = readableWorkbook.getFirstSheet().read().get(0).getCell(0);

    // When
    LocalDateTime readLocalDateTime = cell.asDate();

    // Then
    assertThat(readLocalDateTime, equalTo(writtenLocalDateTime));
}

Here's the output:

java.lang.AssertionError: 
Expected: <1900-01-01T00:00>
     but: was <1900-01-02T00:00>
Expected :<1900-01-01T00:00>
Actual   :<1900-01-02T00:00>

If I write it to a file then open the file in LIbreOffice, the cell correctly displays as 1900-01-01 00:00. See bug.xlsx for the written file.

Thanks in advance.

James.

Also wanted to say what a great library this is. So thank you for all the hard work creating and maintaining it!

OutOfCoffeeError commented 1 year ago

This issue is fixed in one of the latest PRs https://github.com/dhatim/fastexcel/pull/256