You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EvaluationConditionalFormatRule.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ss.formula;
  16. import java.util.ArrayList;
  17. import java.util.Collections;
  18. import java.util.HashMap;
  19. import java.util.HashSet;
  20. import java.util.LinkedHashSet;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import org.apache.poi.ss.formula.eval.BlankEval;
  25. import org.apache.poi.ss.formula.eval.BoolEval;
  26. import org.apache.poi.ss.formula.eval.ErrorEval;
  27. import org.apache.poi.ss.formula.eval.NumberEval;
  28. import org.apache.poi.ss.formula.eval.RefEval;
  29. import org.apache.poi.ss.formula.eval.StringEval;
  30. import org.apache.poi.ss.formula.eval.ValueEval;
  31. import org.apache.poi.ss.formula.functions.AggregateFunction;
  32. import org.apache.poi.ss.usermodel.Cell;
  33. import org.apache.poi.ss.usermodel.CellType;
  34. import org.apache.poi.ss.usermodel.ConditionFilterData;
  35. import org.apache.poi.ss.usermodel.ConditionFilterType;
  36. import org.apache.poi.ss.usermodel.ConditionType;
  37. import org.apache.poi.ss.usermodel.ConditionalFormatting;
  38. import org.apache.poi.ss.usermodel.ConditionalFormattingRule;
  39. import org.apache.poi.ss.usermodel.ExcelNumberFormat;
  40. import org.apache.poi.ss.usermodel.Row;
  41. import org.apache.poi.ss.usermodel.Sheet;
  42. import org.apache.poi.ss.util.CellRangeAddress;
  43. import org.apache.poi.ss.util.CellReference;
  44. /**
  45. * Abstracted and cached version of a Conditional Format rule for use with a
  46. * {@link ConditionalFormattingEvaluator}. This references a rule, its owning
  47. * {@link ConditionalFormatting}, its priority order (lower index = higher priority in Excel),
  48. * and the information needed to evaluate the rule for a given cell.
  49. * <p>
  50. * Having this all combined and cached avoids repeated access calls to the
  51. * underlying structural objects, XSSF CT* objects and HSSF raw byte structures.
  52. * Those objects can be referenced from here. This object will be out of sync if
  53. * anything modifies the referenced structures' evaluation properties.
  54. * <p>
  55. * The assumption is that consuming applications will read the display properties once and
  56. * create whatever style objects they need, caching those at the application level.
  57. * Thus this class only caches values needed for evaluation, not display.
  58. */
  59. /**
  60. *
  61. */
  62. public class EvaluationConditionalFormatRule implements Comparable<EvaluationConditionalFormatRule> {
  63. private final WorkbookEvaluator workbookEvaluator;
  64. private final Sheet sheet;
  65. private final ConditionalFormatting formatting;
  66. private final ConditionalFormattingRule rule;
  67. /* cached values */
  68. private final CellRangeAddress[] regions;
  69. /**
  70. * Depending on the rule type, it may want to know about certain values in the region when evaluating {@link #matches(Cell)},
  71. * such as top 10, unique, duplicate, average, etc. This collection stores those if needed so they are not repeatedly calculated
  72. */
  73. private final Map<CellRangeAddress, Set<ValueAndFormat>> meaningfulRegionValues = new HashMap<CellRangeAddress, Set<ValueAndFormat>>();
  74. private final int priority;
  75. private final int formattingIndex;
  76. private final int ruleIndex;
  77. private final String formula1;
  78. private final String formula2;
  79. private final OperatorEnum operator;
  80. private final ConditionType type;
  81. // cached for performance, to avoid reading the XMLBean every time a conditinally formatted cell is rendered
  82. private final ExcelNumberFormat numberFormat;
  83. /**
  84. *
  85. * @param workbookEvaluator
  86. * @param sheet
  87. * @param formatting
  88. * @param formattingIndex for priority, zero based
  89. * @param rule
  90. * @param ruleIndex for priority, zero based, if this is an HSSF rule. Unused for XSSF rules
  91. * @param regions could be read from formatting, but every call creates new objects in a new array.
  92. * this allows calling it once per formatting instance, and re-using the array.
  93. */
  94. public EvaluationConditionalFormatRule(WorkbookEvaluator workbookEvaluator, Sheet sheet, ConditionalFormatting formatting, int formattingIndex, ConditionalFormattingRule rule, int ruleIndex, CellRangeAddress[] regions) {
  95. super();
  96. this.workbookEvaluator = workbookEvaluator;
  97. this.sheet = sheet;
  98. this.formatting = formatting;
  99. this.rule = rule;
  100. this.formattingIndex = formattingIndex;
  101. this.ruleIndex = ruleIndex;
  102. this.priority = rule.getPriority();
  103. this.regions = regions;
  104. formula1 = rule.getFormula1();
  105. formula2 = rule.getFormula2();
  106. numberFormat = rule.getNumberFormat();
  107. operator = OperatorEnum.values()[rule.getComparisonOperation()];
  108. type = rule.getConditionType();
  109. }
  110. /**
  111. * @return sheet
  112. */
  113. public Sheet getSheet() {
  114. return sheet;
  115. }
  116. /**
  117. * @return the formatting
  118. */
  119. public ConditionalFormatting getFormatting() {
  120. return formatting;
  121. }
  122. /**
  123. * @return conditional formatting index
  124. */
  125. public int getFormattingIndex() {
  126. return formattingIndex;
  127. }
  128. /**
  129. * @return Excel number format string to apply to matching cells, or null to keep the cell default
  130. */
  131. public ExcelNumberFormat getNumberFormat() {
  132. return numberFormat;
  133. }
  134. /**
  135. * @return the rule
  136. */
  137. public ConditionalFormattingRule getRule() {
  138. return rule;
  139. }
  140. /**
  141. * @return rule index
  142. */
  143. public int getRuleIndex() {
  144. return ruleIndex;
  145. }
  146. /**
  147. * @return the regions
  148. */
  149. public CellRangeAddress[] getRegions() {
  150. return regions;
  151. }
  152. /**
  153. * @return the priority
  154. */
  155. public int getPriority() {
  156. return priority;
  157. }
  158. /**
  159. * @return the formula1
  160. */
  161. public String getFormula1() {
  162. return formula1;
  163. }
  164. /**
  165. * @return the formula2
  166. */
  167. public String getFormula2() {
  168. return formula2;
  169. }
  170. /**
  171. * @return the operator
  172. */
  173. public OperatorEnum getOperator() {
  174. return operator;
  175. }
  176. /**
  177. * @return the type
  178. */
  179. public ConditionType getType() {
  180. return type;
  181. }
  182. /**
  183. * Defined as equal sheet name and formatting and rule indexes
  184. * @see java.lang.Object#equals(java.lang.Object)
  185. */
  186. @Override
  187. public boolean equals(Object obj) {
  188. if (obj == null) {
  189. return false;
  190. }
  191. if (! obj.getClass().equals(this.getClass())) {
  192. return false;
  193. }
  194. final EvaluationConditionalFormatRule r = (EvaluationConditionalFormatRule) obj;
  195. return getSheet().getSheetName().equalsIgnoreCase(r.getSheet().getSheetName())
  196. && getFormattingIndex() == r.getFormattingIndex()
  197. && getRuleIndex() == r.getRuleIndex();
  198. }
  199. /**
  200. * Per Excel Help, XSSF rule priority is sheet-wide, not just within the owning ConditionalFormatting object.
  201. * This can be seen by creating 4 rules applying to two different ranges and examining the XML.
  202. * <p>
  203. * HSSF priority is based on definition/persistence order.
  204. *
  205. * @param o
  206. * @return comparison based on sheet name, formatting index, and rule priority
  207. */
  208. @Override
  209. public int compareTo(EvaluationConditionalFormatRule o) {
  210. int cmp = getSheet().getSheetName().compareToIgnoreCase(o.getSheet().getSheetName());
  211. if (cmp != 0) {
  212. return cmp;
  213. }
  214. final int x = getPriority();
  215. final int y = o.getPriority();
  216. // logic from Integer.compare()
  217. cmp = (x < y) ? -1 : ((x == y) ? 0 : 1);
  218. if (cmp != 0) {
  219. return cmp;
  220. }
  221. cmp = new Integer(getFormattingIndex()).compareTo(new Integer(o.getFormattingIndex()));
  222. if (cmp != 0) {
  223. return cmp;
  224. }
  225. return new Integer(getRuleIndex()).compareTo(new Integer(o.getRuleIndex()));
  226. }
  227. @Override
  228. public int hashCode() {
  229. int hash = sheet.getSheetName().hashCode();
  230. hash = 31 * hash + formattingIndex;
  231. hash = 31 * hash + ruleIndex;
  232. return hash;
  233. }
  234. /**
  235. * @param ref
  236. * @return true if this rule evaluates to true for the given cell
  237. */
  238. /* package */ boolean matches(CellReference ref) {
  239. // first check that it is in one of the regions defined for this format
  240. CellRangeAddress region = null;
  241. for (CellRangeAddress r : regions) {
  242. if (r.isInRange(ref)) {
  243. region = r;
  244. break;
  245. }
  246. }
  247. if (region == null) {
  248. // cell not in range of this rule
  249. return false;
  250. }
  251. final ConditionType ruleType = getRule().getConditionType();
  252. // these rules apply to all cells in a region. Specific condition criteria
  253. // may specify no special formatting for that value partition, but that's display logic
  254. if (ruleType.equals(ConditionType.COLOR_SCALE)
  255. || ruleType.equals(ConditionType.DATA_BAR)
  256. || ruleType.equals(ConditionType.ICON_SET)) {
  257. return true;
  258. }
  259. Cell cell = null;
  260. final Row row = sheet.getRow(ref.getRow());
  261. if (row != null) {
  262. cell = row.getCell(ref.getCol());
  263. }
  264. if (ruleType.equals(ConditionType.CELL_VALUE_IS)) {
  265. // undefined cells never match a VALUE_IS condition
  266. if (cell == null) return false;
  267. return checkValue(cell, region);
  268. }
  269. if (ruleType.equals(ConditionType.FORMULA)) {
  270. return checkFormula(ref, region);
  271. }
  272. if (ruleType.equals(ConditionType.FILTER)) {
  273. return checkFilter(cell, ref, region);
  274. }
  275. // TODO: anything else, we don't handle yet, such as top 10
  276. return false;
  277. }
  278. /**
  279. * @param cell the cell to check for
  280. * @param region for adjusting relative formulas
  281. * @return if the value of the cell is valid or not for the formatting rule
  282. */
  283. private boolean checkValue(Cell cell, CellRangeAddress region) {
  284. if (cell == null || DataValidationEvaluator.isType(cell, CellType.BLANK)
  285. || DataValidationEvaluator.isType(cell,CellType.ERROR)
  286. || (DataValidationEvaluator.isType(cell,CellType.STRING)
  287. && (cell.getStringCellValue() == null || cell.getStringCellValue().isEmpty())
  288. )
  289. ) {
  290. return false;
  291. }
  292. ValueEval eval = unwrapEval(workbookEvaluator.evaluate(rule.getFormula1(), ConditionalFormattingEvaluator.getRef(cell), region));
  293. String f2 = rule.getFormula2();
  294. ValueEval eval2 = null;
  295. if (f2 != null && f2.length() > 0) {
  296. eval2 = unwrapEval(workbookEvaluator.evaluate(f2, ConditionalFormattingEvaluator.getRef(cell), region));
  297. }
  298. // we assume the cell has been evaluated, and the current formula value stored
  299. if (DataValidationEvaluator.isType(cell, CellType.BOOLEAN)) {
  300. if (eval instanceof BoolEval && (eval2 == null || eval2 instanceof BoolEval) ) {
  301. return operator.isValid(cell.getBooleanCellValue(), ((BoolEval) eval).getBooleanValue(), eval2 == null ? null : ((BoolEval) eval2).getBooleanValue());
  302. }
  303. return false; // wrong types
  304. }
  305. if (DataValidationEvaluator.isType(cell, CellType.NUMERIC)) {
  306. if (eval instanceof NumberEval && (eval2 == null || eval2 instanceof NumberEval) ) {
  307. return operator.isValid(cell.getNumericCellValue(), ((NumberEval) eval).getNumberValue(), eval2 == null ? null : ((NumberEval) eval2).getNumberValue());
  308. }
  309. return false; // wrong types
  310. }
  311. if (DataValidationEvaluator.isType(cell, CellType.STRING)) {
  312. if (eval instanceof StringEval && (eval2 == null || eval2 instanceof StringEval) ) {
  313. return operator.isValid(cell.getStringCellValue(), ((StringEval) eval).getStringValue(), eval2 == null ? null : ((StringEval) eval2).getStringValue());
  314. }
  315. return false; // wrong types
  316. }
  317. // should not get here, but in case...
  318. return false;
  319. }
  320. private ValueEval unwrapEval(ValueEval eval) {
  321. ValueEval comp = eval;
  322. while (comp instanceof RefEval) {
  323. RefEval ref = (RefEval) comp;
  324. comp = ref.getInnerValueEval(ref.getFirstSheetIndex());
  325. }
  326. return comp;
  327. }
  328. /**
  329. * @param cell needed for offsets from region anchor - may be null!
  330. * @param region for adjusting relative formulas
  331. * @return true/false using the same rules as Data Validation evaluations
  332. */
  333. private boolean checkFormula(CellReference ref, CellRangeAddress region) {
  334. ValueEval comp = unwrapEval(workbookEvaluator.evaluate(rule.getFormula1(), ref, region));
  335. // Copied for now from DataValidationEvaluator.ValidationEnum.FORMULA#isValidValue()
  336. if (comp instanceof BlankEval) {
  337. return true;
  338. }
  339. if (comp instanceof ErrorEval) {
  340. return false;
  341. }
  342. if (comp instanceof BoolEval) {
  343. return ((BoolEval) comp).getBooleanValue();
  344. }
  345. // empirically tested in Excel - 0=false, any other number = true/valid
  346. // see test file DataValidationEvaluations.xlsx
  347. if (comp instanceof NumberEval) {
  348. return ((NumberEval) comp).getNumberValue() != 0;
  349. }
  350. return false; // anything else is false, such as text
  351. }
  352. private boolean checkFilter(Cell cell, CellReference ref, CellRangeAddress region) {
  353. final ConditionFilterType filterType = rule.getConditionFilterType();
  354. if (filterType == null) {
  355. return false;
  356. }
  357. final ValueAndFormat cv = getCellValue(cell);
  358. // TODO: this could/should be delegated to the Enum type, but that's in the usermodel package,
  359. // we may not want evaluation code there. Of course, maybe the enum should go here in formula,
  360. // and not be returned by the SS model, but then we need the XSSF rule to expose the raw OOXML
  361. // type value, which isn't ideal either.
  362. switch (filterType) {
  363. case FILTER:
  364. return false; // we don't evaluate HSSF filters yet
  365. case TOP_10:
  366. // from testing, Excel only operates on numbers and dates (which are stored as numbers) in the range.
  367. // numbers stored as text are ignored, but numbers formatted as text are treated as numbers.
  368. if (! cv.isNumber()) {
  369. return false;
  370. }
  371. return getMeaningfulValues(region, false, new ValueFunction() {
  372. @Override
  373. public Set<ValueAndFormat> evaluate(List<ValueAndFormat> allValues) {
  374. List<ValueAndFormat> values = allValues;
  375. final ConditionFilterData conf = rule.getFilterConfiguration();
  376. if (! conf.getBottom()) {
  377. Collections.sort(values, Collections.reverseOrder());
  378. } else {
  379. Collections.sort(values);
  380. }
  381. int limit = (int) conf.getRank();
  382. if (conf.getPercent()) {
  383. limit = allValues.size() * limit / 100;
  384. }
  385. if (allValues.size() <= limit) {
  386. return new HashSet<ValueAndFormat>(allValues);
  387. }
  388. return new HashSet<ValueAndFormat>(allValues.subList(0, limit));
  389. }
  390. }).contains(cv);
  391. case UNIQUE_VALUES:
  392. // Per Excel help, "duplicate" means matching value AND format
  393. // https://support.office.com/en-us/article/Filter-for-unique-values-or-remove-duplicate-values-ccf664b0-81d6-449b-bbe1-8daaec1e83c2
  394. return getMeaningfulValues(region, true, new ValueFunction() {
  395. @Override
  396. public Set<ValueAndFormat> evaluate(List<ValueAndFormat> allValues) {
  397. List<ValueAndFormat> values = allValues;
  398. Collections.sort(values);
  399. final Set<ValueAndFormat> unique = new HashSet<ValueAndFormat>();
  400. for (int i=0; i < values.size(); i++) {
  401. final ValueAndFormat v = values.get(i);
  402. // skip this if the current value matches the next one, or is the last one and matches the previous one
  403. if ( (i < values.size()-1 && v.equals(values.get(i+1)) ) || ( i > 0 && i == values.size()-1 && v.equals(values.get(i-1)) ) ) {
  404. // current value matches next value, skip both
  405. i++;
  406. continue;
  407. }
  408. unique.add(v);
  409. }
  410. return unique;
  411. }
  412. }).contains(cv);
  413. case DUPLICATE_VALUES:
  414. // Per Excel help, "duplicate" means matching value AND format
  415. // https://support.office.com/en-us/article/Filter-for-unique-values-or-remove-duplicate-values-ccf664b0-81d6-449b-bbe1-8daaec1e83c2
  416. return getMeaningfulValues(region, true, new ValueFunction() {
  417. @Override
  418. public Set<ValueAndFormat> evaluate(List<ValueAndFormat> allValues) {
  419. List<ValueAndFormat> values = allValues;
  420. Collections.sort(values);
  421. final Set<ValueAndFormat> dup = new HashSet<ValueAndFormat>();
  422. for (int i=0; i < values.size(); i++) {
  423. final ValueAndFormat v = values.get(i);
  424. // skip this if the current value matches the next one, or is the last one and matches the previous one
  425. if ( (i < values.size()-1 && v.equals(values.get(i+1)) ) || ( i > 0 && i == values.size()-1 && v.equals(values.get(i-1)) ) ) {
  426. // current value matches next value, add one
  427. dup.add(v);
  428. i++;
  429. }
  430. }
  431. return dup;
  432. }
  433. }).contains(cv);
  434. case ABOVE_AVERAGE:
  435. // from testing, Excel only operates on numbers and dates (which are stored as numbers) in the range.
  436. // numbers stored as text are ignored, but numbers formatted as text are treated as numbers.
  437. final ConditionFilterData conf = rule.getFilterConfiguration();
  438. // actually ordered, so iteration order is predictable
  439. List<ValueAndFormat> values = new ArrayList<ValueAndFormat>(getMeaningfulValues(region, false, new ValueFunction() {
  440. @Override
  441. public Set<ValueAndFormat> evaluate(List<ValueAndFormat> allValues) {
  442. List<ValueAndFormat> values = allValues;
  443. double total = 0;
  444. ValueEval[] pop = new ValueEval[values.size()];
  445. for (int i=0; i < values.size(); i++) {
  446. ValueAndFormat v = values.get(i);
  447. total += v.value.doubleValue();
  448. pop[i] = new NumberEval(v.value.doubleValue());
  449. }
  450. final Set<ValueAndFormat> avgSet = new LinkedHashSet<ValueAndFormat>(1);
  451. avgSet.add(new ValueAndFormat(new Double(values.size() == 0 ? 0 : total / values.size()), null));
  452. final double stdDev = values.size() <= 1 ? 0 : ((NumberEval) AggregateFunction.STDEV.evaluate(pop, 0, 0)).getNumberValue();
  453. avgSet.add(new ValueAndFormat(new Double(stdDev), null));
  454. return avgSet;
  455. }
  456. }));
  457. Double val = cv.isNumber() ? cv.getValue() : null;
  458. if (val == null) {
  459. return false;
  460. }
  461. double avg = values.get(0).value.doubleValue();
  462. double stdDev = values.get(1).value.doubleValue();
  463. /*
  464. * use StdDev, aboveAverage, equalAverage to find:
  465. * comparison value
  466. * operator type
  467. */
  468. Double comp = new Double(conf.getStdDev() > 0 ? (avg + (conf.getAboveAverage() ? 1 : -1) * stdDev * conf.getStdDev()) : avg) ;
  469. OperatorEnum op = null;
  470. if (conf.getAboveAverage()) {
  471. if (conf.getEqualAverage()) {
  472. op = OperatorEnum.GREATER_OR_EQUAL;
  473. } else {
  474. op = OperatorEnum.GREATER_THAN;
  475. }
  476. } else {
  477. if (conf.getEqualAverage()) {
  478. op = OperatorEnum.LESS_OR_EQUAL;
  479. } else {
  480. op = OperatorEnum.LESS_THAN;
  481. }
  482. }
  483. return op != null && op.isValid(val, comp, null);
  484. case CONTAINS_TEXT:
  485. // implemented both by a cfRule "text" attribute and a formula. Use the formula.
  486. return checkFormula(ref, region);
  487. case NOT_CONTAINS_TEXT:
  488. // implemented both by a cfRule "text" attribute and a formula. Use the formula.
  489. return checkFormula(ref, region);
  490. case BEGINS_WITH:
  491. // implemented both by a cfRule "text" attribute and a formula. Use the formula.
  492. return checkFormula(ref, region);
  493. case ENDS_WITH:
  494. // implemented both by a cfRule "text" attribute and a formula. Use the formula.
  495. return checkFormula(ref, region);
  496. case CONTAINS_BLANKS:
  497. try {
  498. String v = cv.getString();
  499. // see TextFunction.TRIM for implementation
  500. return v == null || v.trim().length() == 0;
  501. } catch (Exception e) {
  502. // not a valid string value, and not a blank cell (that's checked earlier)
  503. return false;
  504. }
  505. case NOT_CONTAINS_BLANKS:
  506. try {
  507. String v = cv.getString();
  508. // see TextFunction.TRIM for implementation
  509. return v != null && v.trim().length() > 0;
  510. } catch (Exception e) {
  511. // not a valid string value, but not blank
  512. return true;
  513. }
  514. case CONTAINS_ERRORS:
  515. return cell != null && DataValidationEvaluator.isType(cell, CellType.ERROR);
  516. case NOT_CONTAINS_ERRORS:
  517. return cell == null || ! DataValidationEvaluator.isType(cell, CellType.ERROR);
  518. case TIME_PERIOD:
  519. // implemented both by a cfRule "text" attribute and a formula. Use the formula.
  520. return checkFormula(ref, region);
  521. default:
  522. return false;
  523. }
  524. }
  525. /**
  526. * from testing, Excel only operates on numbers and dates (which are stored as numbers) in the range.
  527. * numbers stored as text are ignored, but numbers formatted as text are treated as numbers.
  528. *
  529. * @param region
  530. * @return the meaningful values in the range of cells specified
  531. */
  532. private Set<ValueAndFormat> getMeaningfulValues(CellRangeAddress region, boolean withText, ValueFunction func) {
  533. Set<ValueAndFormat> values = meaningfulRegionValues.get(region);
  534. if (values != null) {
  535. return values;
  536. }
  537. List<ValueAndFormat> allValues = new ArrayList<ValueAndFormat>((region.getLastColumn() - region.getFirstColumn()+1) * (region.getLastRow() - region.getFirstRow() + 1));
  538. for (int r=region.getFirstRow(); r <= region.getLastRow(); r++) {
  539. final Row row = sheet.getRow(r);
  540. if (row == null) {
  541. continue;
  542. }
  543. for (int c = region.getFirstColumn(); c <= region.getLastColumn(); c++) {
  544. Cell cell = row.getCell(c);
  545. final ValueAndFormat cv = getCellValue(cell);
  546. if (cv != null && (withText || cv.isNumber()) ) {
  547. allValues.add(cv);
  548. }
  549. }
  550. }
  551. values = func.evaluate(allValues);
  552. meaningfulRegionValues.put(region, values);
  553. return values;
  554. }
  555. private ValueAndFormat getCellValue(Cell cell) {
  556. if (cell != null) {
  557. final CellType type = cell.getCellTypeEnum();
  558. if (type == CellType.NUMERIC || (type == CellType.FORMULA && cell.getCachedFormulaResultTypeEnum() == CellType.NUMERIC) ) {
  559. return new ValueAndFormat(new Double(cell.getNumericCellValue()), cell.getCellStyle().getDataFormatString());
  560. } else if (type == CellType.STRING || (type == CellType.FORMULA && cell.getCachedFormulaResultTypeEnum() == CellType.STRING) ) {
  561. return new ValueAndFormat(cell.getStringCellValue(), cell.getCellStyle().getDataFormatString());
  562. } else if (type == CellType.BOOLEAN || (type == CellType.FORMULA && cell.getCachedFormulaResultTypeEnum() == CellType.BOOLEAN) ) {
  563. return new ValueAndFormat(cell.getStringCellValue(), cell.getCellStyle().getDataFormatString());
  564. }
  565. }
  566. return new ValueAndFormat("", "");
  567. }
  568. /**
  569. * instances evaluate the values for a region and return the positive matches for the function type.
  570. * TODO: when we get to use Java 8, this is obviously a Lambda Function.
  571. */
  572. protected interface ValueFunction {
  573. /**
  574. *
  575. * @param values
  576. * @return the desired values for the rules implemented by the current instance
  577. */
  578. Set<ValueAndFormat> evaluate(List<ValueAndFormat> values);
  579. }
  580. /**
  581. * Not calling it OperatorType to avoid confusion for now with other classes.
  582. * Definition order matches OOXML type ID indexes.
  583. * Note that this has NO_COMPARISON as the first item, unlike the similar
  584. * DataValidation operator enum. Thanks, Microsoft.
  585. */
  586. public static enum OperatorEnum {
  587. NO_COMPARISON {
  588. /** always false/invalid */
  589. @Override
  590. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  591. return false;
  592. }
  593. },
  594. BETWEEN {
  595. @Override
  596. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  597. return cellValue.compareTo(v1) >= 0 && cellValue.compareTo(v2) <= 0;
  598. }
  599. },
  600. NOT_BETWEEN {
  601. @Override
  602. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  603. return cellValue.compareTo(v1) < 0 || cellValue.compareTo(v2) > 0;
  604. }
  605. },
  606. EQUAL {
  607. @Override
  608. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  609. // need to avoid instanceof, to work around a 1.6 compiler bug
  610. if (cellValue.getClass() == String.class) {
  611. return cellValue.toString().compareToIgnoreCase(v1.toString()) == 0;
  612. }
  613. return cellValue.compareTo(v1) == 0;
  614. }
  615. },
  616. NOT_EQUAL {
  617. @Override
  618. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  619. // need to avoid instanceof, to work around a 1.6 compiler bug
  620. if (cellValue.getClass() == String.class) {
  621. return cellValue.toString().compareToIgnoreCase(v1.toString()) == 0;
  622. }
  623. return cellValue.compareTo(v1) != 0;
  624. }
  625. },
  626. GREATER_THAN {
  627. @Override
  628. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  629. return cellValue.compareTo(v1) > 0;
  630. }
  631. },
  632. LESS_THAN {
  633. @Override
  634. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  635. return cellValue.compareTo(v1) < 0;
  636. }
  637. },
  638. GREATER_OR_EQUAL {
  639. @Override
  640. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  641. return cellValue.compareTo(v1) >= 0;
  642. }
  643. },
  644. LESS_OR_EQUAL {
  645. @Override
  646. public <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2) {
  647. return cellValue.compareTo(v1) <= 0;
  648. }
  649. },
  650. ;
  651. /**
  652. * Evaluates comparison using operator instance rules
  653. * @param cellValue won't be null, assumption is previous checks handled that
  654. * @param v1 if null, value assumed invalid, anything passes, per Excel behavior
  655. * @param v2 null if not needed. If null when needed, assume anything passes, per Excel behavior
  656. * @return true if the comparison is valid
  657. */
  658. public abstract <C extends Comparable<C>> boolean isValid(C cellValue, C v1, C v2);
  659. }
  660. /**
  661. * Note: this class has a natural ordering that is inconsistent with equals.
  662. */
  663. protected static class ValueAndFormat implements Comparable<ValueAndFormat> {
  664. private final Double value;
  665. private final String string;
  666. private final String format;
  667. public ValueAndFormat(Double value, String format) {
  668. this.value = value;
  669. this.format = format;
  670. string = null;
  671. }
  672. public ValueAndFormat(String value, String format) {
  673. this.value = null;
  674. this.format = format;
  675. string = value;
  676. }
  677. public boolean isNumber() {
  678. return value != null;
  679. }
  680. public Double getValue() {
  681. return value;
  682. }
  683. public String getString() {
  684. return string;
  685. }
  686. @Override
  687. public boolean equals(Object obj) {
  688. if (!(obj instanceof ValueAndFormat)) {
  689. return false;
  690. }
  691. ValueAndFormat o = (ValueAndFormat) obj;
  692. return ( value == o.value || value.equals(o.value))
  693. && ( format == o.format || format.equals(o.format))
  694. && (string == o.string || string.equals(o.string));
  695. }
  696. /**
  697. * Note: this class has a natural ordering that is inconsistent with equals.
  698. * @param o
  699. * @return value comparison
  700. */
  701. @Override
  702. public int compareTo(ValueAndFormat o) {
  703. if (value == null && o.value != null) {
  704. return 1;
  705. }
  706. if (o.value == null && value != null) {
  707. return -1;
  708. }
  709. int cmp = value == null ? 0 : value.compareTo(o.value);
  710. if (cmp != 0) {
  711. return cmp;
  712. }
  713. if (string == null && o.string != null) {
  714. return 1;
  715. }
  716. if (o.string == null && string != null) {
  717. return -1;
  718. }
  719. return string == null ? 0 : string.compareTo(o.string);
  720. }
  721. @Override
  722. public int hashCode() {
  723. return (string == null ? 0 : string.hashCode()) * 37 * 37 + 37 * (value == null ? 0 : value.hashCode()) + (format == null ? 0 : format.hashCode());
  724. }
  725. }
  726. }