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 30KB

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