Search in sources :

Example 1 with CellReference

use of org.apache.poi.ss.util.CellReference in project poi by apache.

the class ExcelAntWorkbookUtil method getCell.

/**
     * Returns a cell reference based on a String in standard Excel format
     * (SheetName!CellId).  This method will create a new cell if the
     * requested cell isn't initialized yet.
     *
     * @param cellName
     * @return
     */
private Cell getCell(String cellName) {
    CellReference cellRef = new CellReference(cellName);
    String sheetName = cellRef.getSheetName();
    Sheet sheet = workbook.getSheet(sheetName);
    if (sheet == null) {
        throw new BuildException("Sheet not found: " + sheetName);
    }
    int rowIdx = cellRef.getRow();
    int colIdx = cellRef.getCol();
    Row row = sheet.getRow(rowIdx);
    if (row == null) {
        row = sheet.createRow(rowIdx);
    }
    Cell cell = row.getCell(colIdx);
    if (cell == null) {
        cell = row.createCell(colIdx);
    }
    return cell;
}
Also used : BuildException(org.apache.tools.ant.BuildException) Row(org.apache.poi.ss.usermodel.Row) CellReference(org.apache.poi.ss.util.CellReference) Sheet(org.apache.poi.ss.usermodel.Sheet) Cell(org.apache.poi.ss.usermodel.Cell)

Example 2 with CellReference

use of org.apache.poi.ss.util.CellReference in project poi by apache.

the class FormulaRecordAggregate method isPartOfArrayFormula.

public boolean isPartOfArrayFormula() {
    if (_sharedFormulaRecord != null) {
        return false;
    }
    CellReference expRef = _formulaRecord.getFormula().getExpReference();
    ArrayRecord arec = expRef == null ? null : _sharedValueManager.getArrayRecord(expRef.getRow(), expRef.getCol());
    return arec != null;
}
Also used : ArrayRecord(org.apache.poi.hssf.record.ArrayRecord) CellReference(org.apache.poi.ss.util.CellReference)

Example 3 with CellReference

use of org.apache.poi.ss.util.CellReference in project poi by apache.

the class SharedValueManager method getRecordForFirstCell.

/**
	 * Gets the {@link SharedValueRecordBase} record if it should be encoded immediately after the
	 * formula record contained in the specified {@link FormulaRecordAggregate} agg.  Note - the
	 * shared value record always appears after the first formula record in the group.  For arrays
	 * and tables the first formula is always the in the top left cell.  However, since shared
	 * formula groups can be sparse and/or overlap, the first formula may not actually be in the
	 * top left cell.
	 *
	 * @return the SHRFMLA, TABLE or ARRAY record for the formula cell, if it is the first cell of
	 * a table or array region. <code>null</code> if the formula cell is not shared/array/table,
	 * or if the specified formula is not the the first in the group.
	 */
public SharedValueRecordBase getRecordForFirstCell(FormulaRecordAggregate agg) {
    CellReference firstCell = agg.getFormulaRecord().getFormula().getExpReference();
    // and/or distinguishing between tExp and tTbl.
    if (firstCell == null) {
        // not a shared/array/table formula
        return null;
    }
    int row = firstCell.getRow();
    int column = firstCell.getCol();
    if (agg.getRow() != row || agg.getColumn() != column) {
        // not the first formula cell in the group
        return null;
    }
    if (!_groupsBySharedFormulaRecord.isEmpty()) {
        SharedFormulaGroup sfg = findFormulaGroupForCell(firstCell);
        if (null != sfg) {
            return sfg.getSFR();
        }
    }
    for (TableRecord tr : _tableRecords) {
        if (tr.isFirstCell(row, column)) {
            return tr;
        }
    }
    for (ArrayRecord ar : _arrayRecords) {
        if (ar.isFirstCell(row, column)) {
            return ar;
        }
    }
    return null;
}
Also used : ArrayRecord(org.apache.poi.hssf.record.ArrayRecord) CellReference(org.apache.poi.ss.util.CellReference) TableRecord(org.apache.poi.hssf.record.TableRecord)

Example 4 with CellReference

use of org.apache.poi.ss.util.CellReference in project poi by apache.

the class FormulaRecordAggregate method getArrayFormulaRange.

public CellRangeAddress getArrayFormulaRange() {
    if (_sharedFormulaRecord != null) {
        throw new IllegalStateException("not an array formula cell.");
    }
    CellReference expRef = _formulaRecord.getFormula().getExpReference();
    if (expRef == null) {
        throw new IllegalStateException("not an array formula cell.");
    }
    ArrayRecord arec = _sharedValueManager.getArrayRecord(expRef.getRow(), expRef.getCol());
    if (arec == null) {
        throw new IllegalStateException("ArrayRecord was not found for the locator " + expRef.formatAsString());
    }
    CellRangeAddress8Bit a = arec.getRange();
    return new CellRangeAddress(a.getFirstRow(), a.getLastRow(), a.getFirstColumn(), a.getLastColumn());
}
Also used : ArrayRecord(org.apache.poi.hssf.record.ArrayRecord) CellRangeAddress8Bit(org.apache.poi.hssf.util.CellRangeAddress8Bit) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress) CellReference(org.apache.poi.ss.util.CellReference)

Example 5 with CellReference

use of org.apache.poi.ss.util.CellReference in project poi by apache.

the class WorkbookEvaluator method evaluateFormula.

// visibility raised for testing
@Internal
/* package */
ValueEval evaluateFormula(OperationEvaluationContext ec, Ptg[] ptgs) {
    // always init. to non-null just for defensive avoiding NPE
    String dbgIndentStr = "";
    if (dbgEvaluationOutputForNextEval) {
        // first evaluation call when ouput is desired, so iit. this evaluator instance
        dbgEvaluationOutputIndent = 1;
        dbgEvaluationOutputForNextEval = false;
    }
    if (dbgEvaluationOutputIndent > 0) {
        // init. indent string to needed spaces (create as substring vom very long space-only string;
        // limit indendation for deep recursions)
        dbgIndentStr = "                                                                                                    ";
        dbgIndentStr = dbgIndentStr.substring(0, Math.min(dbgIndentStr.length(), dbgEvaluationOutputIndent * 2));
        EVAL_LOG.log(POILogger.WARN, dbgIndentStr + "- evaluateFormula('" + ec.getRefEvaluatorForCurrentSheet().getSheetNameRange() + "'/" + new CellReference(ec.getRowIndex(), ec.getColumnIndex()).formatAsString() + "): " + Arrays.toString(ptgs).replaceAll("\\Qorg.apache.poi.ss.formula.ptg.\\E", ""));
        dbgEvaluationOutputIndent++;
    }
    Stack<ValueEval> stack = new Stack<ValueEval>();
    for (int i = 0, iSize = ptgs.length; i < iSize; i++) {
        // since we don't know how to handle these yet :(
        Ptg ptg = ptgs[i];
        if (dbgEvaluationOutputIndent > 0) {
            EVAL_LOG.log(POILogger.INFO, dbgIndentStr + "  * ptg " + i + ": " + ptg + ", stack: " + stack);
        }
        if (ptg instanceof AttrPtg) {
            AttrPtg attrPtg = (AttrPtg) ptg;
            if (attrPtg.isSum()) {
                // Excel prefers to encode 'SUM()' as a tAttr token, but this evaluator
                // expects the equivalent function token
                ptg = FuncVarPtg.SUM;
            }
            if (attrPtg.isOptimizedChoose()) {
                ValueEval arg0 = stack.pop();
                int[] jumpTable = attrPtg.getJumpTable();
                int dist;
                int nChoices = jumpTable.length;
                try {
                    int switchIndex = Choose.evaluateFirstArg(arg0, ec.getRowIndex(), ec.getColumnIndex());
                    if (switchIndex < 1 || switchIndex > nChoices) {
                        stack.push(ErrorEval.VALUE_INVALID);
                        // +4 for tFuncFar(CHOOSE)
                        dist = attrPtg.getChooseFuncOffset() + 4;
                    } else {
                        dist = jumpTable[switchIndex - 1];
                    }
                } catch (EvaluationException e) {
                    stack.push(e.getErrorEval());
                    // +4 for tFuncFar(CHOOSE)
                    dist = attrPtg.getChooseFuncOffset() + 4;
                }
                // Encoded dist for tAttrChoose includes size of jump table, but
                // countTokensToBeSkipped() does not (it counts whole tokens).
                // subtract jump table size
                dist -= nChoices * 2 + 2;
                i += countTokensToBeSkipped(ptgs, i, dist);
                continue;
            }
            if (attrPtg.isOptimizedIf()) {
                ValueEval arg0 = stack.pop();
                boolean evaluatedPredicate;
                try {
                    evaluatedPredicate = IfFunc.evaluateFirstArg(arg0, ec.getRowIndex(), ec.getColumnIndex());
                } catch (EvaluationException e) {
                    stack.push(e.getErrorEval());
                    int dist = attrPtg.getData();
                    i += countTokensToBeSkipped(ptgs, i, dist);
                    attrPtg = (AttrPtg) ptgs[i];
                    dist = attrPtg.getData() + 1;
                    i += countTokensToBeSkipped(ptgs, i, dist);
                    continue;
                }
                if (evaluatedPredicate) {
                // nothing to skip - true param follows
                } else {
                    int dist = attrPtg.getData();
                    i += countTokensToBeSkipped(ptgs, i, dist);
                    Ptg nextPtg = ptgs[i + 1];
                    if (ptgs[i] instanceof AttrPtg && nextPtg instanceof FuncVarPtg && // if we really have the IF next or some other FuncVarPtg as third param, e.g. ROW()/COLUMN()!
                    ((FuncVarPtg) nextPtg).getFunctionIndex() == FunctionMetadataRegistry.FUNCTION_INDEX_IF) {
                        // this is an if statement without a false param (as opposed to MissingArgPtg as the false param)
                        i++;
                        stack.push(BoolEval.FALSE);
                    }
                }
                continue;
            }
            if (attrPtg.isSkip()) {
                int dist = attrPtg.getData() + 1;
                i += countTokensToBeSkipped(ptgs, i, dist);
                if (stack.peek() == MissingArgEval.instance) {
                    stack.pop();
                    stack.push(BlankEval.instance);
                }
                continue;
            }
        }
        if (ptg instanceof ControlPtg) {
            // skip Parentheses, Attr, etc
            continue;
        }
        if (ptg instanceof MemFuncPtg || ptg instanceof MemAreaPtg) {
            // can ignore, rest of tokens for this expression are in OK RPN order
            continue;
        }
        if (ptg instanceof MemErrPtg) {
            continue;
        }
        if (ptg instanceof UnionPtg) {
            ValueEval v2 = stack.pop();
            ValueEval v1 = stack.pop();
            stack.push(new RefListEval(v1, v2));
            continue;
        }
        ValueEval opResult;
        if (ptg instanceof OperationPtg) {
            OperationPtg optg = (OperationPtg) ptg;
            int numops = optg.getNumberOfOperands();
            ValueEval[] ops = new ValueEval[numops];
            // storing the ops in reverse order since they are popping
            for (int j = numops - 1; j >= 0; j--) {
                ValueEval p = stack.pop();
                ops[j] = p;
            }
            //                logDebug("invoke " + operation + " (nAgs=" + numops + ")");
            opResult = OperationEvaluatorFactory.evaluate(optg, ops, ec);
        } else {
            opResult = getEvalForPtg(ptg, ec);
        }
        if (opResult == null) {
            throw new RuntimeException("Evaluation result must not be null");
        }
        //            logDebug("push " + opResult);
        stack.push(opResult);
        if (dbgEvaluationOutputIndent > 0) {
            EVAL_LOG.log(POILogger.INFO, dbgIndentStr + "    = " + opResult);
        }
    }
    ValueEval value = stack.pop();
    if (!stack.isEmpty()) {
        throw new IllegalStateException("evaluation stack not empty");
    }
    ValueEval result = dereferenceResult(value, ec.getRowIndex(), ec.getColumnIndex());
    if (dbgEvaluationOutputIndent > 0) {
        EVAL_LOG.log(POILogger.INFO, dbgIndentStr + "finshed eval of " + new CellReference(ec.getRowIndex(), ec.getColumnIndex()).formatAsString() + ": " + result);
        dbgEvaluationOutputIndent--;
        if (dbgEvaluationOutputIndent == 1) {
            // this evaluation is done, reset indent to stop logging
            dbgEvaluationOutputIndent = -1;
        }
    }
    // if
    return result;
}
Also used : CellReference(org.apache.poi.ss.util.CellReference) Stack(java.util.Stack) Internal(org.apache.poi.util.Internal)

Aggregations

CellReference (org.apache.poi.ss.util.CellReference)125 Test (org.junit.Test)52 Cell (org.apache.poi.ss.usermodel.Cell)28 Row (org.apache.poi.ss.usermodel.Row)27 AreaReference (org.apache.poi.ss.util.AreaReference)20 Sheet (org.apache.poi.ss.usermodel.Sheet)18 Workbook (org.apache.poi.ss.usermodel.Workbook)14 CellRangeAddress (org.apache.poi.ss.util.CellRangeAddress)14 HSSFWorkbook (org.apache.poi.hssf.usermodel.HSSFWorkbook)13 SXSSFWorkbook (org.apache.poi.xssf.streaming.SXSSFWorkbook)12 XSSFWorkbook (org.apache.poi.xssf.usermodel.XSSFWorkbook)11 FormulaEvaluator (org.apache.poi.ss.usermodel.FormulaEvaluator)8 XSSFSheet (org.apache.poi.xssf.usermodel.XSSFSheet)8 CellStyle (org.apache.poi.ss.usermodel.CellStyle)7 ArrayList (java.util.ArrayList)6 IOException (java.io.IOException)5 HSSFSheet (org.apache.poi.hssf.usermodel.HSSFSheet)5 RichTextString (org.apache.poi.ss.usermodel.RichTextString)5 FileOutputStream (java.io.FileOutputStream)4 OutputStream (java.io.OutputStream)4