monitorjbl / excel-streaming-reader

An easy-to-use implementation of a streaming Excel reader using Apache POI
Apache License 2.0
951 stars 343 forks source link

cell.getStringCellValue() returns incorrect value when the cell is the type of formula #191

Open CMemorY180819 opened 5 years ago

CMemorY180819 commented 5 years ago

Hello~~

First of all thank you very much for this awesome library. It's seems very cool~

Unfortunately there are some problems when I'm using.

For example, c5 cell has formula =c4 and when c4 cell is blank, I use cell.getStringCellValue() to read c5 and it returns me 0. Actually, what I want is also blank.

I'm using version 2.1.0 and I'm trying to fix it by myself, but any help would be highly appreciated.

apixandru commented 5 years ago

I can't reproduce the issue, looks like cell evaluation works the same in 'native' mode as in the streaming mode. formula_empty_cell.xlsx

package com.monitorjbl.xlsx;

import org.apache.poi.ss.usermodel.*;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import static com.monitorjbl.xlsx.TestUtils.nextRow;

public class FormulaTests {

    @BeforeClass
    public static void init() {
        Locale.setDefault(Locale.ENGLISH);
    }

    @Test
    public void testTypes() throws Exception {
        try (InputStream stream = TestUtils.class.getResourceAsStream("/formula_empty_cell.xlsx")) {
            check(WorkbookFactory.create(stream));
        }
        try (InputStream stream = TestUtils.class.getResourceAsStream("/formula_empty_cell.xlsx")) {
            final Workbook workbook = StreamingReader.builder()
                    .open(stream);
            check(workbook);
        }
    }

    private void check(Workbook sheets1) throws IOException {
        try (final Workbook sheets = sheets1) {
            Sheet sheet = sheets.getSheetAt(0);
            Row row = nextRow(sheet.rowIterator());
            Cell emptyCell = row.getCell(0);
            System.out.println("Cell: " + emptyCell);

            Cell emptyCellReference = row.getCell(1);
            System.out.println("Cell formula: " + emptyCellReference.getCellFormula());
            System.out.println("Cell formula evaluation: " + emptyCellReference.getStringCellValue());
        }
    }
}
mawen12 commented 5 years ago

You can try.

cell.setCellType(Cell.CELL_TYPE_STRING);
String value = cell.getStringCellValue();