You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@poi.apache.org by fa...@apache.org on 2026/09/20 16:13:02 UTC
(poi) branch trunk updated: [bug-65059] SUMIF/COUNTIF/AVERAGEIF and the *IFS functions: an array of criteria gives an array of results (#1323)
This is an automated email from the ASF dual-hosted git repository.
pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git
The following commit(s) were added to refs/heads/trunk by this push:
new 7c466e4ed4 [bug-65059] SUMIF/COUNTIF/AVERAGEIF and the *IFS functions: an array of criteria gives an array of results (#1323)
7c466e4ed4 is described below
commit 7c466e4ed4f416c5ac8b93785db199e76dac3fb9
Author: PJ Fanning <pj...@users.noreply.github.com>
AuthorDate: Sun Sep 20 17:12:56 2026 +0100
[bug-65059] SUMIF/COUNTIF/AVERAGEIF and the *IFS functions: an array of criteria gives an array of results (#1323)
When the criteria argument stands for several criteria, Excel evaluates the
conditional aggregate once per criterion and returns an array, which the
enclosing function consumes: SUMPRODUCT(SUMIFS(sum,range,criteria_range)),
SUM(COUNTIF(range,{"a","b"})), MAX(COUNTIFS(...)), INDEX(...). That is the
case for an array constant or computed array always, and for a multi-cell
range in array context (inside an array-mode function such as SUMPRODUCT, or
in an array formula). In an ordinary cell a range criteria keeps being reduced
to the formula's own row, as Excel does (FormulaEvalTestData.xls relies on it).
Before, the *IFS functions summed the per-criterion results whatever the
enclosing function (right for SUM, wrong for weighted SUMPRODUCT, MAX,
AVERAGE, INDEX ...) and whatever the context, and SUMIF/COUNTIF/AVERAGEIF
reduced an array of criteria to one value even inside SUMPRODUCT. Several
array criteria are paired element-wise and must have the same shape.
Co-authored-by: Claude Opus 5 <no...@anthropic.com>
---
.../apache/poi/ss/formula/functions/AverageIf.java | 19 +-
.../apache/poi/ss/formula/functions/Baseifs.java | 94 ++++++---
.../apache/poi/ss/formula/functions/Countif.java | 79 +++++++-
.../org/apache/poi/ss/formula/functions/Sumif.java | 34 +++-
...TestConditionalAggregatesWithArrayCriteria.java | 221 +++++++++++++++++++++
5 files changed, 414 insertions(+), 33 deletions(-)
diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/AverageIf.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/AverageIf.java
index dfc0239f76..6c2e74f8d6 100644
--- a/poi/src/main/java/org/apache/poi/ss/formula/functions/AverageIf.java
+++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/AverageIf.java
@@ -46,13 +46,28 @@ public class AverageIf extends Baseifs {
// collect pairs of ranges and criteria
AreaEval ae = convertRangeArg(args[0]);
- I_MatchPredicate mp = Countif.createCriteriaPredicate(args[1], ec.getRowIndex(), ec.getColumnIndex());
+ if (args[1] instanceof AreaEval crit && crit.getHeight() * crit.getWidth() > 1
+ && Countif.isArrayCriteria(crit, isArrayContext(ec))) {
+ // one result per criterion
+ AreaEval finalSumRange = sumRange;
+ return Countif.evaluateForEachCriterion((AreaEval) args[1],
+ criterion -> averageIf(finalSumRange, ae, criterion, ec));
+ }
+ return averageIf(sumRange, ae, args[1], ec);
+ } catch (EvaluationException e) {
+ return e.getErrorEval();
+ }
+ }
+
+ private ValueEval averageIf(AreaEval sumRange, AreaEval testRange, ValueEval criteria, OperationEvaluationContext ec) {
+ try {
+ I_MatchPredicate mp = Countif.createCriteriaPredicate(criteria, ec.getRowIndex(), ec.getColumnIndex());
if (mp instanceof Countif.ErrorMatcher errorMatcher) {
throw new EvaluationException(ErrorEval.valueOf(errorMatcher.getValue()));
}
- return aggregateMatchingCells(createAggregator(), sumRange, ae, mp);
+ return aggregateMatchingCells(createAggregator(), sumRange, testRange, mp);
} catch (EvaluationException e) {
return e.getErrorEval();
}
diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/Baseifs.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/Baseifs.java
index db00396069..0f70ebad37 100644
--- a/poi/src/main/java/org/apache/poi/ss/formula/functions/Baseifs.java
+++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/Baseifs.java
@@ -20,10 +20,12 @@
package org.apache.poi.ss.formula.functions;
import org.apache.poi.ss.formula.OperationEvaluationContext;
+import org.apache.poi.ss.formula.CacheAreaEval;
+import org.apache.poi.ss.formula.EvaluationCell;
+import org.apache.poi.ss.formula.EvaluationSheet;
import org.apache.poi.ss.formula.eval.AreaEval;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.EvaluationException;
-import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.eval.RefEval;
import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.formula.functions.CountUtils.I_MatchPredicate;
@@ -75,34 +77,20 @@ import org.apache.poi.ss.formula.functions.Countif.ErrorMatcher;
validateCriteriaRanges(sumRange, ae);
- // If any criteria argument is a multi-element array (e.g. {1,2,3} or a
- // multi-cell range), expand it: evaluate once per element and sum the
- // results. This supports SUM(COUNTIFS(range, {v1,v2,...})) patterns where
- // the implicit-intersection approach used by getSingleValue would either
- // yield the wrong single value or produce an ERROR when the formula cell
- // lies outside the array's row/column bounds (Bug 70005).
+ // A criteria argument may stand for several criteria (an array constant such as {1,2},
+ // or in array context a multi-cell range such as D1:D3, see Countif.isArrayCriteria):
+ // Excel then evaluates the function once per element and returns an array of the
+ // results, which is what SUMPRODUCT(SUMIFS(sum,range,criteria_range)),
+ // SUM(COUNTIFS(range,{v1,v2})) and MAX(COUNTIFS(...)) rely on. Several array criteria
+ // are paired element-wise and must have the same shape.
+ Boolean arrayContext = null; // looked up only when a criteria argument is an array at all
for (int k = 0; k < numPairs; k++) {
- if (criteriaArgs[k] instanceof AreaEval arrayCrit) {
- if (arrayCrit.getHeight() * arrayCrit.getWidth() > 1) {
- double total = 0.0;
- for (int r = 0; r < arrayCrit.getHeight(); r++) {
- for (int c = 0; c < arrayCrit.getWidth(); c++) {
- ValueEval element = arrayCrit.getRelativeValue(r, c);
- I_MatchPredicate[] mp = new I_MatchPredicate[numPairs];
- for (int j = 0; j < numPairs; j++) {
- mp[j] = Countif.createCriteriaPredicate(
- j == k ? element : criteriaArgs[j],
- ec.getRowIndex(), ec.getColumnIndex());
- }
- validateCriteria(mp);
- ValueEval partial = aggregateMatchingCells(createAggregator(), sumRange, ae, mp);
- if (partial instanceof ErrorEval) return partial;
- if (partial instanceof NumberEval ne) {
- total += ne.getNumberValue();
- }
- }
- }
- return new NumberEval(total);
+ if (criteriaArgs[k] instanceof AreaEval crit && crit.getHeight() * crit.getWidth() > 1) {
+ if (arrayContext == null) {
+ arrayContext = isArrayContext(ec);
+ }
+ if (Countif.isArrayCriteria(crit, arrayContext)) {
+ return evaluateForEachCriterion(sumRange, ae, criteriaArgs, crit, arrayContext, ec);
}
}
}
@@ -119,6 +107,56 @@ import org.apache.poi.ss.formula.functions.Countif.ErrorMatcher;
}
}
+ /**
+ * @return whether the function is evaluated in array context: its result feeds an array-mode
+ * function such as SUMPRODUCT, or the formula cell is part of an array formula
+ * @since 6.0.0
+ */
+ /* package */ static boolean isArrayContext(OperationEvaluationContext ec) {
+ if (ec.isArraymode()) {
+ return true;
+ }
+ if (ec.getWorkbook() == null || ec.getSheetIndex() < 0) {
+ // a context without a cell (tests, conditional formatting, data validation)
+ return false;
+ }
+ EvaluationSheet sheet = ec.getWorkbook().getSheet(ec.getSheetIndex());
+ EvaluationCell cell = sheet.getCell(ec.getRowIndex(), ec.getColumnIndex());
+ return cell != null && cell.isPartOfArrayFormulaGroup();
+ }
+
+ private ValueEval evaluateForEachCriterion(AreaEval sumRange, AreaEval[] ranges, ValueEval[] criteriaArgs,
+ AreaEval shape, boolean arrayContext, OperationEvaluationContext ec) throws EvaluationException {
+ int height = shape.getHeight();
+ int width = shape.getWidth();
+ for (ValueEval criteria : criteriaArgs) {
+ if (Countif.isArrayCriteria(criteria, arrayContext)
+ && (((AreaEval) criteria).getHeight() != height || ((AreaEval) criteria).getWidth() != width)) {
+ throw EvaluationException.invalidValue();
+ }
+ }
+ ValueEval[] results = new ValueEval[height * width];
+ for (int r = 0; r < height; r++) {
+ for (int c = 0; c < width; c++) {
+ I_MatchPredicate[] mp = new I_MatchPredicate[criteriaArgs.length];
+ for (int j = 0; j < criteriaArgs.length; j++) {
+ ValueEval criterion = Countif.isArrayCriteria(criteriaArgs[j], arrayContext)
+ ? ((AreaEval) criteriaArgs[j]).getRelativeValue(r, c) : criteriaArgs[j];
+ mp[j] = Countif.createCriteriaPredicate(criterion, ec.getRowIndex(), ec.getColumnIndex());
+ }
+ ValueEval result;
+ try {
+ validateCriteria(mp);
+ result = aggregateMatchingCells(createAggregator(), sumRange, ranges, mp);
+ } catch (EvaluationException e) {
+ result = e.getErrorEval();
+ }
+ results[r * width + c] = result;
+ }
+ }
+ return new CacheAreaEval(shape.getFirstRow(), shape.getFirstColumn(), shape.getLastRow(), shape.getLastColumn(), results);
+ }
+
/**
* Verify that each <code>criteriaRanges</code> argument contains the same number of rows and columns
* including the <code>sumRange</code> argument if present
diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/Countif.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/Countif.java
index 652f60b0a4..46e2064ce9 100644
--- a/poi/src/main/java/org/apache/poi/ss/formula/functions/Countif.java
+++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/Countif.java
@@ -20,6 +20,8 @@ package org.apache.poi.ss.formula.functions;
import java.util.regex.Pattern;
import org.apache.poi.ss.formula.ThreeDEval;
+import org.apache.poi.ss.formula.CacheAreaEval;
+import org.apache.poi.ss.formula.eval.AreaEval;
import org.apache.poi.ss.formula.eval.BlankEval;
import org.apache.poi.ss.formula.eval.BoolEval;
import org.apache.poi.ss.formula.eval.ErrorEval;
@@ -43,7 +45,7 @@ import org.apache.poi.util.StringUtil;
* <tr><th>criteria</th><td>is used to determine which cells to count</td></tr>
* </table>
*/
-public final class Countif extends Fixed2ArgFunction {
+public final class Countif extends Fixed2ArgFunction implements ArrayFunction {
private static final class CmpOp {
public static final int NONE = 0;
@@ -400,7 +402,10 @@ public final class Countif extends Fixed2ArgFunction {
@Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
-
+ if (isArrayCriteria(arg1, false)) {
+ return evaluateForEachCriterion((AreaEval) arg1,
+ criterion -> evaluate(srcRowIndex, srcColumnIndex, arg0, criterion));
+ }
I_MatchPredicate mp = createCriteriaPredicate(arg1, srcRowIndex, srcColumnIndex);
if(mp == null) {
// If the criteria arg is a reference to a blank cell, countif always returns zero.
@@ -412,6 +417,76 @@ public final class Countif extends Fixed2ArgFunction {
return e.getErrorEval();
}
}
+
+ /**
+ * Evaluated in array context (the result feeds an array-mode function such as SUMPRODUCT, or
+ * the cell is part of an array formula): a multi-cell range as criteria means one count per
+ * criterion.
+ * @since 6.0.0
+ */
+ @Override
+ public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
+ if (args.length != 2) {
+ return ErrorEval.VALUE_INVALID;
+ }
+ if (isArrayCriteria(args[1], true)) {
+ return evaluateForEachCriterion((AreaEval) args[1],
+ criterion -> evaluate(srcRowIndex, srcColumnIndex, args[0], criterion));
+ }
+ return evaluate(srcRowIndex, srcColumnIndex, args[0], args[1]);
+ }
+
+ /**
+ * Decides whether a criteria argument stands for several criteria, so that the function is
+ * evaluated once per element and returns an array of the results (what
+ * {@code SUMPRODUCT(SUMIF(range,criteria_range,sum_range))} and
+ * {@code SUM(COUNTIF(range,{"a","b"}))} rely on), the way Excel does it:
+ * <ul>
+ * <li>an array constant or a computed array ({@code {"a","b"}}, {@code IF(...)}) always is;</li>
+ * <li>a multi-cell range is only in array context - inside an array-mode function such as
+ * SUMPRODUCT, or in an array formula. In an ordinary cell a range criteria is reduced to the
+ * cell on the formula's own row or column (implicit intersection), as Excel does there.</li>
+ * </ul>
+ *
+ * @param arrayContext whether the function is being evaluated in array context
+ * @since 6.0.0
+ */
+ /* package */ static boolean isArrayCriteria(ValueEval criteria, boolean arrayContext) {
+ if (!(criteria instanceof AreaEval ae) || ae.getHeight() * ae.getWidth() <= 1) {
+ return false;
+ }
+ return arrayContext || criteria instanceof CacheAreaEval;
+ }
+
+ /**
+ * The evaluation of a conditional aggregate for one criterion, used to evaluate it for each
+ * element of an array of criteria.
+ * @since 6.0.0
+ */
+ /* package */ interface CriterionEvaluation {
+ ValueEval evaluate(ValueEval criterion);
+ }
+
+ /**
+ * Evaluates a conditional aggregate once per element of an array of criteria and returns the
+ * results as an array of the same shape (and, for a range, the same position, so that a plain
+ * formula cell picks the element on its own row the way Excel's implicit intersection does).
+ * This is what makes {@code SUMPRODUCT(SUMIF(range,criteria_range,sum_range))},
+ * {@code SUM(COUNTIF(range,{"a","b"}))} and the like work.
+ * @since 6.0.0
+ */
+ /* package */ static ValueEval evaluateForEachCriterion(AreaEval criteria, CriterionEvaluation evaluation) {
+ int height = criteria.getHeight();
+ int width = criteria.getWidth();
+ ValueEval[] results = new ValueEval[height * width];
+ for (int r = 0; r < height; r++) {
+ for (int c = 0; c < width; c++) {
+ results[r * width + c] = evaluation.evaluate(criteria.getRelativeValue(r, c));
+ }
+ }
+ return new CacheAreaEval(criteria.getFirstRow(), criteria.getFirstColumn(),
+ criteria.getLastRow(), criteria.getLastColumn(), results);
+ }
/**
* @return the number of evaluated cells in the range that match the specified criteria
*/
diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/Sumif.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/Sumif.java
index a0e3bc6066..f87ba49462 100644
--- a/poi/src/main/java/org/apache/poi/ss/formula/functions/Sumif.java
+++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/Sumif.java
@@ -37,7 +37,7 @@ import org.apache.poi.ss.formula.functions.CountUtils.I_MatchPredicate;
* <tr><th>sum_range</th><td>Locates the top-left corner of the corresponding range of addends - values to be added (after being selected by the criteria)</td></tr>
* </table><br>
*/
-public final class Sumif extends Var2or3ArgFunction {
+public final class Sumif extends Var2or3ArgFunction implements ArrayFunction {
@Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
@@ -66,7 +66,39 @@ public final class Sumif extends Var2or3ArgFunction {
return eval(srcRowIndex, srcColumnIndex, arg1, aeRange, aeSum);
}
+ /**
+ * Evaluated in array context (the result feeds an array-mode function such as SUMPRODUCT, or
+ * the cell is part of an array formula): a multi-cell range as criteria means one sum per
+ * criterion.
+ * @since 6.0.0
+ */
+ @Override
+ public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
+ if (args.length < 2 || args.length > 3) {
+ return ErrorEval.VALUE_INVALID;
+ }
+ AreaEval aeRange;
+ AreaEval aeSum;
+ try {
+ aeRange = convertRangeArg(args[0]);
+ aeSum = args.length == 3 ? createSumRange(args[2], aeRange) : aeRange;
+ } catch (EvaluationException e) {
+ return e.getErrorEval();
+ }
+ return eval(srcRowIndex, srcColumnIndex, args[1], aeRange, aeSum, true);
+ }
+
private static ValueEval eval(int srcRowIndex, int srcColumnIndex, ValueEval arg1, AreaEval aeRange, AreaEval aeSum) {
+ return eval(srcRowIndex, srcColumnIndex, arg1, aeRange, aeSum, false);
+ }
+
+ private static ValueEval eval(int srcRowIndex, int srcColumnIndex, ValueEval arg1, AreaEval aeRange, AreaEval aeSum,
+ boolean arrayContext) {
+ if (Countif.isArrayCriteria(arg1, arrayContext)) {
+ // one result per criterion
+ return Countif.evaluateForEachCriterion((AreaEval) arg1,
+ criterion -> eval(srcRowIndex, srcColumnIndex, criterion, aeRange, aeSum, false));
+ }
I_MatchPredicate mp = Countif.createCriteriaPredicate(arg1, srcRowIndex, srcColumnIndex);
if (mp == null) {
return NumberEval.ZERO;
diff --git a/poi/src/test/java/org/apache/poi/ss/formula/functions/TestConditionalAggregatesWithArrayCriteria.java b/poi/src/test/java/org/apache/poi/ss/formula/functions/TestConditionalAggregatesWithArrayCriteria.java
new file mode 100644
index 0000000000..f162c28132
--- /dev/null
+++ b/poi/src/test/java/org/apache/poi/ss/formula/functions/TestConditionalAggregatesWithArrayCriteria.java
@@ -0,0 +1,221 @@
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+==================================================================== */
+
+package org.apache.poi.ss.formula.functions;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.IOException;
+
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellType;
+import org.apache.poi.ss.usermodel.CellValue;
+import org.apache.poi.ss.usermodel.FormulaError;
+import org.apache.poi.ss.usermodel.FormulaEvaluator;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Bug 65059: when the criteria argument of SUMIF, COUNTIF, AVERAGEIF, SUMIFS, COUNTIFS,
+ * AVERAGEIFS, MAXIFS or MINIFS stands for several criteria, Excel evaluates the function once per
+ * criterion and returns an array of the results, which the enclosing function (SUMPRODUCT, SUM,
+ * MAX, INDEX ...) then consumes. That is the case for an array constant such as {@code {"a","b"}}
+ * always, and for a multi-cell range in array context: inside an array-mode function such as
+ * SUMPRODUCT, or in an array formula. In an ordinary cell a range criteria is reduced to the cell
+ * on the formula's own row (implicit intersection), as Excel does - the Excel-generated
+ * {@code FormulaEvalTestData.xls} relies on that.
+ * <p>
+ * POI used to sum the per-criterion results of the *IFS functions whatever the context, and to
+ * reduce the criteria of the single-condition functions to one value whatever the context.
+ * <pre>
+ * A(formulas) B C D E
+ * 1 1 x x 1
+ * 2 2 x x 2
+ * 3 3 y x 3
+ * 4 4 y z 4
+ * </pre>
+ */
+class TestConditionalAggregatesWithArrayCriteria {
+
+ private HSSFWorkbook wb;
+ private Sheet sheet;
+ private FormulaEvaluator fe;
+
+ @BeforeEach
+ void setUp() {
+ wb = new HSSFWorkbook();
+ sheet = wb.createSheet("S");
+ String[] c = {"x", "x", "y", "y"};
+ String[] d = {"x", "x", "x", "z"};
+ for (int r = 0; r < 4; r++) {
+ Row row = sheet.createRow(r);
+ row.createCell(1).setCellValue(r + 1);
+ row.createCell(2).setCellValue(c[r]);
+ row.createCell(3).setCellValue(d[r]);
+ row.createCell(4).setCellValue(r + 1);
+ }
+ sheet.createRow(9);
+ fe = wb.getCreationHelper().createFormulaEvaluator();
+ }
+
+ @AfterEach
+ void tearDown() throws IOException {
+ wb.close();
+ }
+
+ private CellValue evalIn(int rowIndex, String formula) {
+ Cell cell = sheet.getRow(rowIndex).createCell(0);
+ cell.setCellFormula(formula);
+ fe.clearAllCachedResultValues();
+ return fe.evaluate(cell);
+ }
+
+ private CellValue evalAsArrayFormula(String formula) {
+ sheet.setArrayFormula(formula, CellRangeAddress.valueOf("G1"));
+ fe.clearAllCachedResultValues();
+ CellValue cv = fe.evaluate(sheet.getRow(0).getCell(6));
+ sheet.removeArrayFormula(sheet.getRow(0).getCell(6));
+ return cv;
+ }
+
+ private void assertPlain(int rowIndex, double expected, String formula) {
+ CellValue cv = evalIn(rowIndex, formula);
+ assertEquals(CellType.NUMERIC, cv.getCellType(), formula + " on row " + (rowIndex + 1) + " -> " + cv);
+ assertEquals(expected, cv.getNumberValue(), 1e-9, formula + " on row " + (rowIndex + 1));
+ }
+
+ private void assertArrayFormula(double expected, String formula) {
+ CellValue cv = evalAsArrayFormula(formula);
+ assertEquals(CellType.NUMERIC, cv.getCellType(), "{=" + formula + "} -> " + cv);
+ assertEquals(expected, cv.getNumberValue(), 1e-9, "{=" + formula + "}");
+ }
+
+ /** the formula gives the same number on row 1, on a row below the data and as an array formula */
+ private void assertNumber(double expected, String formula) {
+ for (int r : new int[]{0, 9}) {
+ CellValue cv = evalIn(r, formula);
+ assertEquals(CellType.NUMERIC, cv.getCellType(), formula + " on row " + (r + 1) + " -> " + cv);
+ assertEquals(expected, cv.getNumberValue(), 1e-9, formula + " on row " + (r + 1));
+ }
+ CellValue cv = evalAsArrayFormula(formula);
+ assertEquals(CellType.NUMERIC, cv.getCellType(), "{=" + formula + "} -> " + cv);
+ assertEquals(expected, cv.getNumberValue(), 1e-9, "{=" + formula + "}");
+ }
+
+ @Test
+ void bug65059SumproductOfSumifsWithARangeAsCriteria() {
+ // one SUMIFS per criterion in D1:D4: x -> 1+2, x -> 3, x -> 3, z -> 0
+ assertNumber(3 + 3 + 3 + 0, "SUMPRODUCT(SUMIFS(B1:B4,C1:C4,D1:D4))");
+ // x -> 3, x -> 3, y -> 3
+ assertNumber(3 + 3 + 3, "SUMPRODUCT(SUMIFS(B1:B3,C1:C3,C1:C3))");
+ }
+
+ @Test
+ void bug65059ReportersCase() {
+ // B = 1, 2, 3; C = D = 1, 1, 1: each of the three criteria matches every row
+ Sheet s = wb.createSheet("Report");
+ for (int r = 0; r < 3; r++) {
+ Row row = s.createRow(r);
+ row.createCell(1).setCellValue(r + 1);
+ row.createCell(2).setCellValue(1);
+ row.createCell(3).setCellValue(1);
+ }
+ Cell plain = s.getRow(0).createCell(0);
+ plain.setCellFormula("SUMPRODUCT(SUMIFS(B1:B3, C1:C3, D1:D3))");
+ assertEquals(18, fe.evaluate(plain).getNumberValue(), 1e-9);
+ s.setArrayFormula("SUMPRODUCT(SUMIFS(B1:B3, C1:C3, D1:D3))", CellRangeAddress.valueOf("A2"));
+ assertEquals(18, fe.evaluate(s.getRow(1).getCell(0)).getNumberValue(), 1e-9);
+ }
+
+ @Test
+ void theResultIsAnArrayNotASum() {
+ // weighted by E: 3*1 + 3*2 + 3*3 + 0*4
+ assertNumber(3 + 6 + 9, "SUMPRODUCT(SUMIFS(B1:B4,C1:C4,D1:D4),E1:E4)");
+ // COUNTIFS per criterion: 2, 2, 2, 0
+ assertArrayFormula(2, "MAX(COUNTIFS(C1:C4,D1:D4))");
+ assertArrayFormula(0, "MIN(COUNTIFS(C1:C4,D1:D4))");
+ assertArrayFormula(6, "SUM(COUNTIFS(C1:C4,D1:D4))");
+ // AVERAGEIFS per criterion: 1.5, 1.5, 1.5 and #DIV/0! for z, which has no match
+ assertNumber(1.5, "INDEX(AVERAGEIFS(B1:B4,C1:C4,D1:D4),2)");
+ assertArrayFormula(4.5, "SUM(AVERAGEIFS(B1:B3,C1:C3,D1:D3))");
+ assertNumber(3 + 4, "INDEX(SUMIFS(B1:B4,C1:C4,{\"x\",\"y\"}),2)");
+ }
+
+ @Test
+ void arrayConstantsAsCriteria() {
+ // SUM(COUNTIFS(range,{...})) - bug 70005 - keeps working, as do the other aggregates
+ assertNumber(2 + 2, "SUM(COUNTIFS(C1:C4,{\"x\",\"y\"}))");
+ assertNumber(3 + 7, "SUM(SUMIFS(B1:B4,C1:C4,{\"x\",\"y\"}))");
+ assertNumber(7, "MAX(SUMIFS(B1:B4,C1:C4,{\"x\",\"y\"}))");
+ assertNumber(3 + 7, "SUM(SUMIF(C1:C4,{\"x\",\"y\"},B1:B4))");
+ assertNumber(2 + 2, "SUM(COUNTIF(C1:C4,{\"x\",\"y\"}))");
+ // a criterion with no match contributes 0 / an empty count
+ assertNumber(3, "SUM(SUMIF(C1:C4,{\"x\",\"q\"},B1:B4))");
+ }
+
+ @Test
+ void singleConditionFunctionsWithARangeAsCriteria() {
+ // SUMIF per criterion in D: x -> 3, x -> 3, x -> 3, z -> 0
+ assertNumber(9, "SUMPRODUCT(SUMIF(C1:C4,D1:D4,B1:B4))");
+ assertNumber(3 * 2, "SUMPRODUCT(COUNTIF(C1:C4,D1:D4))");
+ assertArrayFormula(1.5, "MAX(AVERAGEIF(C1:C3,D1:D3,B1:B3))");
+ // SUMIF without a sum range sums the tested range itself: E is numeric, criteria from E
+ assertNumber(1 + 2 + 3 + 4, "SUMPRODUCT(SUMIF(E1:E4,E1:E4))");
+ }
+
+ @Test
+ void severalArrayCriteriaArePairedElementWise() {
+ // (C=x and D=x) -> 2, (C=x and D=x) -> 2, (C=y and D=x) -> 1, (C=y and D=z) -> 1
+ assertNumber(2 + 2 + 1 + 1, "SUMPRODUCT(COUNTIFS(C1:C4,C1:C4,D1:D4,D1:D4))");
+ assertArrayFormula(2, "MAX(COUNTIFS(C1:C4,C1:C4,D1:D4,D1:D4))");
+ // arrays of different shapes cannot be paired
+ CellValue cv = evalIn(9, "SUMPRODUCT(COUNTIFS(C1:C4,C1:C4,D1:D4,{\"x\",\"z\"}))");
+ assertEquals(CellType.ERROR, cv.getCellType());
+ assertEquals(FormulaError.VALUE, FormulaError.forInt(cv.getErrorValue()));
+ }
+
+ @Test
+ void aRangeCriteriaInAnOrdinaryCellIsImplicitlyIntersected() {
+ // outside array context Excel reduces the criteria range to the formula's row: D1 = x
+ assertPlain(0, 3, "SUMIFS(B1:B4,C1:C4,D1:D4)");
+ assertPlain(3, 0, "SUMIFS(B1:B4,C1:C4,D1:D4)");
+ assertPlain(1, 3, "SUMIF(C1:C4,D1:D4,B1:B4)");
+ assertPlain(0, 2, "SUM(COUNTIFS(C1:C4,D1:D4))");
+ // ... and on a row the range does not cover the criterion is the #VALUE! error, which for
+ // SUMIF matches only cells holding that error (FormulaEvalTestData.xls, SUMIF row)
+ assertPlain(9, 0, "SUMIF(C1:C4,D1:D4,B1:B4)");
+ // the same formulas in array context see every criterion
+ assertArrayFormula(9, "SUMPRODUCT(SUMIFS(B1:B4,C1:C4,D1:D4))");
+ assertArrayFormula(6, "SUM(COUNTIFS(C1:C4,D1:D4))");
+ }
+
+ @Test
+ void scalarCriteriaAreUnchanged() {
+ assertNumber(3, "SUMIFS(B1:B4,C1:C4,\"x\")");
+ assertNumber(2, "COUNTIFS(C1:C4,\"x\",D1:D4,\"x\")");
+ assertNumber(3, "SUMIF(C1:C4,\"x\",B1:B4)");
+ assertNumber(3, "SUMIF(C1:C4,D1,B1:B4)");
+ assertNumber(1.5, "AVERAGEIFS(B1:B4,C1:C4,\"x\",D1:D4,\"x\")");
+ assertNumber(4, "MAXIFS(B1:B4,C1:C4,\"y\")");
+ assertNumber(3, "MINIFS(B1:B4,C1:C4,\"y\")");
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org