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.

CellFormatPart.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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.format;
  16. import org.apache.poi.hssf.util.HSSFColor;
  17. import javax.swing.*;
  18. import java.awt.*;
  19. import java.util.Locale;
  20. import java.util.Map;
  21. import java.util.TreeMap;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;
  24. import static org.apache.poi.ss.format.CellFormatter.logger;
  25. import static org.apache.poi.ss.format.CellFormatter.quote;
  26. /**
  27. * Objects of this class represent a single part of a cell format expression.
  28. * Each cell can have up to four of these for positive, zero, negative, and text
  29. * values.
  30. * <p/>
  31. * Each format part can contain a color, a condition, and will always contain a
  32. * format specification. For example <tt>"[Red][>=10]#"</tt> has a color
  33. * (<tt>[Red]</tt>), a condition (<tt>>=10</tt>) and a format specification
  34. * (<tt>#</tt>).
  35. * <p/>
  36. * This class also contains patterns for matching the subparts of format
  37. * specification. These are used internally, but are made public in case other
  38. * code has use for them.
  39. *
  40. * @author Ken Arnold, Industrious Media LLC
  41. */
  42. public class CellFormatPart {
  43. private final Color color;
  44. private CellFormatCondition condition;
  45. private final CellFormatter format;
  46. private final CellFormatType type;
  47. private static final Map<String, Color> NAMED_COLORS;
  48. static {
  49. NAMED_COLORS = new TreeMap<String, Color>(
  50. String.CASE_INSENSITIVE_ORDER);
  51. Map<Integer,HSSFColor> colors = HSSFColor.getIndexHash();
  52. for (HSSFColor color : colors.values()) {
  53. Class<? extends HSSFColor> type = color.getClass();
  54. String name = type.getSimpleName();
  55. if (name.equals(name.toUpperCase(Locale.ROOT))) {
  56. short[] rgb = color.getTriplet();
  57. Color c = new Color(rgb[0], rgb[1], rgb[2]);
  58. NAMED_COLORS.put(name, c);
  59. if (name.indexOf('_') > 0)
  60. NAMED_COLORS.put(name.replace('_', ' '), c);
  61. if (name.indexOf("_PERCENT") > 0)
  62. NAMED_COLORS.put(name.replace("_PERCENT", "%").replace('_',
  63. ' '), c);
  64. }
  65. }
  66. }
  67. /** Pattern for the color part of a cell format part. */
  68. public static final Pattern COLOR_PAT;
  69. /** Pattern for the condition part of a cell format part. */
  70. public static final Pattern CONDITION_PAT;
  71. /** Pattern for the format specification part of a cell format part. */
  72. public static final Pattern SPECIFICATION_PAT;
  73. /** Pattern for the currency symbol part of a cell format part */
  74. public static final Pattern CURRENCY_PAT;
  75. /** Pattern for an entire cell single part. */
  76. public static final Pattern FORMAT_PAT;
  77. /** Within {@link #FORMAT_PAT}, the group number for the matched color. */
  78. public static final int COLOR_GROUP;
  79. /**
  80. * Within {@link #FORMAT_PAT}, the group number for the operator in the
  81. * condition.
  82. */
  83. public static final int CONDITION_OPERATOR_GROUP;
  84. /**
  85. * Within {@link #FORMAT_PAT}, the group number for the value in the
  86. * condition.
  87. */
  88. public static final int CONDITION_VALUE_GROUP;
  89. /**
  90. * Within {@link #FORMAT_PAT}, the group number for the format
  91. * specification.
  92. */
  93. public static final int SPECIFICATION_GROUP;
  94. static {
  95. // A condition specification
  96. String condition = "([<>=]=?|!=|<>) # The operator\n" +
  97. " \\s*([0-9]+(?:\\.[0-9]*)?)\\s* # The constant to test against\n";
  98. // A currency symbol / string, in a specific locale
  99. String currency = "(\\[\\$.{0,3}-[0-9a-f]{3}\\])";
  100. String color =
  101. "\\[(black|blue|cyan|green|magenta|red|white|yellow|color [0-9]+)\\]";
  102. // A number specification
  103. // Note: careful that in something like ##, that the trailing comma is not caught up in the integer part
  104. // A part of a specification
  105. String part = "\\\\. # Quoted single character\n" +
  106. "|\"([^\\\\\"]|\\\\.)*\" # Quoted string of characters (handles escaped quotes like \\\") \n" +
  107. "|"+currency+" # Currency symbol in a given locale\n" +
  108. "|_. # Space as wide as a given character\n" +
  109. "|\\*. # Repeating fill character\n" +
  110. "|@ # Text: cell text\n" +
  111. "|([0?\\#](?:[0?\\#,]*)) # Number: digit + other digits and commas\n" +
  112. "|e[-+] # Number: Scientific: Exponent\n" +
  113. "|m{1,5} # Date: month or minute spec\n" +
  114. "|d{1,4} # Date: day/date spec\n" +
  115. "|y{2,4} # Date: year spec\n" +
  116. "|h{1,2} # Date: hour spec\n" +
  117. "|s{1,2} # Date: second spec\n" +
  118. "|am?/pm? # Date: am/pm spec\n" +
  119. "|\\[h{1,2}\\] # Elapsed time: hour spec\n" +
  120. "|\\[m{1,2}\\] # Elapsed time: minute spec\n" +
  121. "|\\[s{1,2}\\] # Elapsed time: second spec\n" +
  122. "|[^;] # A character\n" + "";
  123. String format = "(?:" + color + ")? # Text color\n" +
  124. "(?:\\[" + condition + "\\])? # Condition\n" +
  125. // see https://msdn.microsoft.com/en-ca/goglobal/bb964664.aspx and https://bz.apache.org/ooo/show_bug.cgi?id=70003
  126. // we ignore these for now though
  127. "(?:\\[\\$-[0-9a-fA-F]+\\])? # Optional locale id, ignored currently\n" +
  128. "((?:" + part + ")+) # Format spec\n";
  129. int flags = Pattern.COMMENTS | Pattern.CASE_INSENSITIVE;
  130. COLOR_PAT = Pattern.compile(color, flags);
  131. CONDITION_PAT = Pattern.compile(condition, flags);
  132. SPECIFICATION_PAT = Pattern.compile(part, flags);
  133. CURRENCY_PAT = Pattern.compile(currency, flags);
  134. FORMAT_PAT = Pattern.compile(format, flags);
  135. // Calculate the group numbers of important groups. (They shift around
  136. // when the pattern is changed; this way we figure out the numbers by
  137. // experimentation.)
  138. COLOR_GROUP = findGroup(FORMAT_PAT, "[Blue]@", "Blue");
  139. CONDITION_OPERATOR_GROUP = findGroup(FORMAT_PAT, "[>=1]@", ">=");
  140. CONDITION_VALUE_GROUP = findGroup(FORMAT_PAT, "[>=1]@", "1");
  141. SPECIFICATION_GROUP = findGroup(FORMAT_PAT, "[Blue][>1]\\a ?", "\\a ?");
  142. }
  143. interface PartHandler {
  144. String handlePart(Matcher m, String part, CellFormatType type,
  145. StringBuffer desc);
  146. }
  147. /**
  148. * Create an object to represent a format part.
  149. *
  150. * @param desc The string to parse.
  151. */
  152. public CellFormatPart(String desc) {
  153. Matcher m = FORMAT_PAT.matcher(desc);
  154. if (!m.matches()) {
  155. throw new IllegalArgumentException("Unrecognized format: " + quote(
  156. desc));
  157. }
  158. color = getColor(m);
  159. condition = getCondition(m);
  160. type = getCellFormatType(m);
  161. format = getFormatter(m);
  162. }
  163. /**
  164. * Returns <tt>true</tt> if this format part applies to the given value. If
  165. * the value is a number and this is part has a condition, returns
  166. * <tt>true</tt> only if the number passes the condition. Otherwise, this
  167. * always return <tt>true</tt>.
  168. *
  169. * @param valueObject The value to evaluate.
  170. *
  171. * @return <tt>true</tt> if this format part applies to the given value.
  172. */
  173. public boolean applies(Object valueObject) {
  174. if (condition == null || !(valueObject instanceof Number)) {
  175. if (valueObject == null)
  176. throw new NullPointerException("valueObject");
  177. return true;
  178. } else {
  179. Number num = (Number) valueObject;
  180. return condition.pass(num.doubleValue());
  181. }
  182. }
  183. /**
  184. * Returns the number of the first group that is the same as the marker
  185. * string. Starts from group 1.
  186. *
  187. * @param pat The pattern to use.
  188. * @param str The string to match against the pattern.
  189. * @param marker The marker value to find the group of.
  190. *
  191. * @return The matching group number.
  192. *
  193. * @throws IllegalArgumentException No group matches the marker.
  194. */
  195. private static int findGroup(Pattern pat, String str, String marker) {
  196. Matcher m = pat.matcher(str);
  197. if (!m.find())
  198. throw new IllegalArgumentException(
  199. "Pattern \"" + pat.pattern() + "\" doesn't match \"" + str +
  200. "\"");
  201. for (int i = 1; i <= m.groupCount(); i++) {
  202. String grp = m.group(i);
  203. if (grp != null && grp.equals(marker))
  204. return i;
  205. }
  206. throw new IllegalArgumentException(
  207. "\"" + marker + "\" not found in \"" + pat.pattern() + "\"");
  208. }
  209. /**
  210. * Returns the color specification from the matcher, or <tt>null</tt> if
  211. * there is none.
  212. *
  213. * @param m The matcher for the format part.
  214. *
  215. * @return The color specification or <tt>null</tt>.
  216. */
  217. private static Color getColor(Matcher m) {
  218. String cdesc = m.group(COLOR_GROUP);
  219. if (cdesc == null || cdesc.length() == 0)
  220. return null;
  221. Color c = NAMED_COLORS.get(cdesc);
  222. if (c == null)
  223. logger.warning("Unknown color: " + quote(cdesc));
  224. return c;
  225. }
  226. /**
  227. * Returns the condition specification from the matcher, or <tt>null</tt> if
  228. * there is none.
  229. *
  230. * @param m The matcher for the format part.
  231. *
  232. * @return The condition specification or <tt>null</tt>.
  233. */
  234. private CellFormatCondition getCondition(Matcher m) {
  235. String mdesc = m.group(CONDITION_OPERATOR_GROUP);
  236. if (mdesc == null || mdesc.length() == 0)
  237. return null;
  238. return CellFormatCondition.getInstance(m.group(
  239. CONDITION_OPERATOR_GROUP), m.group(CONDITION_VALUE_GROUP));
  240. }
  241. /**
  242. * Returns the CellFormatType object implied by the format specification for
  243. * the format part.
  244. *
  245. * @param matcher The matcher for the format part.
  246. *
  247. * @return The CellFormatType.
  248. */
  249. private CellFormatType getCellFormatType(Matcher matcher) {
  250. String fdesc = matcher.group(SPECIFICATION_GROUP);
  251. return formatType(fdesc);
  252. }
  253. /**
  254. * Returns the formatter object implied by the format specification for the
  255. * format part.
  256. *
  257. * @param matcher The matcher for the format part.
  258. *
  259. * @return The formatter.
  260. */
  261. private CellFormatter getFormatter(Matcher matcher) {
  262. String fdesc = matcher.group(SPECIFICATION_GROUP);
  263. // For now, we don't support localised currencies, so simplify if there
  264. Matcher currencyM = CURRENCY_PAT.matcher(fdesc);
  265. if (currencyM.find()) {
  266. String currencyPart = currencyM.group(1);
  267. String currencyRepl;
  268. if (currencyPart.startsWith("[$-")) {
  269. // Default $ in a different locale
  270. currencyRepl = "$";
  271. } else {
  272. currencyRepl = currencyPart.substring(2, currencyPart.lastIndexOf('-'));
  273. }
  274. fdesc = fdesc.replace(currencyPart, currencyRepl);
  275. }
  276. // Build a formatter for this simplified string
  277. return type.formatter(fdesc);
  278. }
  279. /**
  280. * Returns the type of format.
  281. *
  282. * @param fdesc The format specification
  283. *
  284. * @return The type of format.
  285. */
  286. private CellFormatType formatType(String fdesc) {
  287. fdesc = fdesc.trim();
  288. if (fdesc.equals("") || fdesc.equalsIgnoreCase("General"))
  289. return CellFormatType.GENERAL;
  290. Matcher m = SPECIFICATION_PAT.matcher(fdesc);
  291. boolean couldBeDate = false;
  292. boolean seenZero = false;
  293. while (m.find()) {
  294. String repl = m.group(0);
  295. if (repl.length() > 0) {
  296. char c1 = repl.charAt(0);
  297. char c2 = 0;
  298. if (repl.length() > 1)
  299. c2 = Character.toLowerCase(repl.charAt(1));
  300. switch (c1) {
  301. case '@':
  302. return CellFormatType.TEXT;
  303. case 'd':
  304. case 'D':
  305. case 'y':
  306. case 'Y':
  307. return CellFormatType.DATE;
  308. case 'h':
  309. case 'H':
  310. case 'm':
  311. case 'M':
  312. case 's':
  313. case 'S':
  314. // These can be part of date, or elapsed
  315. couldBeDate = true;
  316. break;
  317. case '0':
  318. // This can be part of date, elapsed, or number
  319. seenZero = true;
  320. break;
  321. case '[':
  322. if (c2 == 'h' || c2 == 'm' || c2 == 's') {
  323. return CellFormatType.ELAPSED;
  324. }
  325. if (c2 == '$') {
  326. // Localised currency
  327. return CellFormatType.NUMBER;
  328. }
  329. // Something else inside [] which isn't supported!
  330. throw new IllegalArgumentException("Unsupported [] format block '" +
  331. repl + "' in '" + fdesc + "' with c2: " + c2);
  332. case '#':
  333. case '?':
  334. return CellFormatType.NUMBER;
  335. }
  336. }
  337. }
  338. // Nothing definitive was found, so we figure out it deductively
  339. if (couldBeDate)
  340. return CellFormatType.DATE;
  341. if (seenZero)
  342. return CellFormatType.NUMBER;
  343. return CellFormatType.TEXT;
  344. }
  345. /**
  346. * Returns a version of the original string that has any special characters
  347. * quoted (or escaped) as appropriate for the cell format type. The format
  348. * type object is queried to see what is special.
  349. *
  350. * @param repl The original string.
  351. * @param type The format type representation object.
  352. *
  353. * @return A version of the string with any special characters replaced.
  354. *
  355. * @see CellFormatType#isSpecial(char)
  356. */
  357. static String quoteSpecial(String repl, CellFormatType type) {
  358. StringBuilder sb = new StringBuilder();
  359. for (int i = 0; i < repl.length(); i++) {
  360. char ch = repl.charAt(i);
  361. if (ch == '\'' && type.isSpecial('\'')) {
  362. sb.append('\u0000');
  363. continue;
  364. }
  365. boolean special = type.isSpecial(ch);
  366. if (special)
  367. sb.append("'");
  368. sb.append(ch);
  369. if (special)
  370. sb.append("'");
  371. }
  372. return sb.toString();
  373. }
  374. /**
  375. * Apply this format part to the given value. This returns a {@link
  376. * CellFormatResult} object with the results.
  377. *
  378. * @param value The value to apply this format part to.
  379. *
  380. * @return A {@link CellFormatResult} object containing the results of
  381. * applying the format to the value.
  382. */
  383. public CellFormatResult apply(Object value) {
  384. boolean applies = applies(value);
  385. String text;
  386. Color textColor;
  387. if (applies) {
  388. text = format.format(value);
  389. textColor = color;
  390. } else {
  391. text = format.simpleFormat(value);
  392. textColor = null;
  393. }
  394. return new CellFormatResult(applies, text, textColor);
  395. }
  396. /**
  397. * Apply this format part to the given value, applying the result to the
  398. * given label.
  399. *
  400. * @param label The label
  401. * @param value The value to apply this format part to.
  402. *
  403. * @return <tt>true</tt> if the
  404. */
  405. public CellFormatResult apply(JLabel label, Object value) {
  406. CellFormatResult result = apply(value);
  407. label.setText(result.text);
  408. if (result.textColor != null) {
  409. label.setForeground(result.textColor);
  410. }
  411. return result;
  412. }
  413. /**
  414. * Returns the CellFormatType object implied by the format specification for
  415. * the format part.
  416. *
  417. * @return The CellFormatType.
  418. */
  419. CellFormatType getCellFormatType() {
  420. return type;
  421. }
  422. /**
  423. * Returns <tt>true</tt> if this format part has a condition.
  424. *
  425. * @return <tt>true</tt> if this format part has a condition.
  426. */
  427. boolean hasCondition() {
  428. return condition != null;
  429. }
  430. public static StringBuffer parseFormat(String fdesc, CellFormatType type,
  431. PartHandler partHandler) {
  432. // Quoting is very awkward. In the Java classes, quoting is done
  433. // between ' chars, with '' meaning a single ' char. The problem is that
  434. // in Excel, it is legal to have two adjacent escaped strings. For
  435. // example, consider the Excel format "\a\b#". The naive (and easy)
  436. // translation into Java DecimalFormat is "'a''b'#". For the number 17,
  437. // in Excel you would get "ab17", but in Java it would be "a'b17" -- the
  438. // '' is in the middle of the quoted string in Java. So the trick we
  439. // use is this: When we encounter a ' char in the Excel format, we
  440. // output a \u0000 char into the string. Now we know that any '' in the
  441. // output is the result of two adjacent escaped strings. So after the
  442. // main loop, we have to do two passes: One to eliminate any ''
  443. // sequences, to make "'a''b'" become "'ab'", and another to replace any
  444. // \u0000 with '' to mean a quote char. Oy.
  445. //
  446. // For formats that don't use "'" we don't do any of this
  447. Matcher m = SPECIFICATION_PAT.matcher(fdesc);
  448. StringBuffer fmt = new StringBuffer();
  449. while (m.find()) {
  450. String part = group(m, 0);
  451. if (part.length() > 0) {
  452. String repl = partHandler.handlePart(m, part, type, fmt);
  453. if (repl == null) {
  454. switch (part.charAt(0)) {
  455. case '\"':
  456. repl = quoteSpecial(part.substring(1,
  457. part.length() - 1), type);
  458. break;
  459. case '\\':
  460. repl = quoteSpecial(part.substring(1), type);
  461. break;
  462. case '_':
  463. repl = " ";
  464. break;
  465. case '*': //!! We don't do this for real, we just put in 3 of them
  466. repl = expandChar(part);
  467. break;
  468. default:
  469. repl = part;
  470. break;
  471. }
  472. }
  473. m.appendReplacement(fmt, Matcher.quoteReplacement(repl));
  474. }
  475. }
  476. m.appendTail(fmt);
  477. if (type.isSpecial('\'')) {
  478. // Now the next pass for quoted characters: Remove '' chars, making "'a''b'" into "'ab'"
  479. int pos = 0;
  480. while ((pos = fmt.indexOf("''", pos)) >= 0) {
  481. fmt.delete(pos, pos + 2);
  482. }
  483. // Now the final pass for quoted chars: Replace any \u0000 with ''
  484. pos = 0;
  485. while ((pos = fmt.indexOf("\u0000", pos)) >= 0) {
  486. fmt.replace(pos, pos + 1, "''");
  487. }
  488. }
  489. return fmt;
  490. }
  491. /**
  492. * Expands a character. This is only partly done, because we don't have the
  493. * correct info. In Excel, this would be expanded to fill the rest of the
  494. * cell, but we don't know, in general, what the "rest of the cell" is.
  495. *
  496. * @param part The character to be repeated is the second character in this
  497. * string.
  498. *
  499. * @return The character repeated three times.
  500. */
  501. static String expandChar(String part) {
  502. String repl;
  503. char ch = part.charAt(1);
  504. repl = "" + ch + ch + ch;
  505. return repl;
  506. }
  507. /**
  508. * Returns the string from the group, or <tt>""</tt> if the group is
  509. * <tt>null</tt>.
  510. *
  511. * @param m The matcher.
  512. * @param g The group number.
  513. *
  514. * @return The group or <tt>""</tt>.
  515. */
  516. public static String group(Matcher m, int g) {
  517. String str = m.group(g);
  518. return (str == null ? "" : str);
  519. }
  520. public String toString() {
  521. return format.format;
  522. }
  523. }