Home » excel » java – Apache POI string formula error

java – Apache POI string formula error

Posted by: admin April 23, 2020 Leave a comment


I use Apache POI to create Excel file with string formula and get #VALUE! error in result file.

Source code is

public static void main(String[] args) throws IOException {
    Workbook wb = new HSSFWorkbook();
    FormulaEvaluator ev = wb.getCreationHelper().createFormulaEvaluator();
    Sheet ws = wb.createSheet();
    Row row = ws.createRow(0);
    Cell cell;
    cell = row.createCell(0);

    cell = row.createCell(1);
    printCellInfo(row.getCell(1),"before formula");
    cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),\" \")");

    printCellInfo(row.getCell(1), "after formula");
    printCellInfo(row.getCell(1), "after recalc");

    OutputStream os = new FileOutputStream("xx.xls");


(printCellInfo is info method I tell below)
and the error cell is B1. Excel says “value used in cell has incorrect data type“.
BUT if open this cell to edit (using F2) and press Enter – formula calculates correctly!!!

Now about cell info. Helping method is

static void printCellInfo(Cell cell, String infoText) {
    System.out.println("Cell "+CellReference.convertNumToColString(cell.getColumnIndex())+cell.getRowIndex()+" "+infoText);
    int ct = cell.getCellType();
    System.out.println("  Cell type "+ct);
    if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        ct = cell.getCachedFormulaResultType();
        System.out.println("  Cached type "+ct);
    switch (ct) {
        case Cell.CELL_TYPE_NUMERIC: 
            System.out.println("  Number <"+cell.getNumericCellValue()+">");
        case Cell.CELL_TYPE_STRING:
            System.out.println(" String <"+cell.getStringCellValue()+">");

and output of main execution is

Cell B0 before formula
  Cell type 3
Cell B0 after formula
  Cell type 2
  Cached type 0
  Number <0.0>
Cell B0 after recalc
  Cell type 2
  Cached type 1
 String <ab>

So B0 is BLANK at first and NUMBER after formula insertion. Why POI do so and maybe problem starts here?
Unfortunately, correct datatype in POI after recalculation does not become correct in excel.

By the way, formulas set from POI IF(A1<>””,”A”,”B”) or MID(A1,1,2) are calculated correct.
And B1=MID(A1,1,2) and C1=IF(A1<>””,B1,” “), set from POI is calculated correct true.

Any ideas? I found the only topic https://openclassrooms.com/forum/sujet/apache-poi-formula-valeur over the internet, there are some ideas, but no working solution…

cell = row.getCell(1);

does not help too.

How to&Answers:

I tried your code on my machine and it is working fine.

I am using beta POI 3.13 on Excel for mac 2013

Your excel sheet is also working fine (after you gave it to me in chat)

so the problem is wrong compatibilities between your POI version and you Excel 2010 libraries.

This is your sheet as well.

enter image description here