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

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