Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

CellFormatPart.java 22KB

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