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.

DataFormatter.java 45KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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. 2012 - Alfresco Software, Ltd.
  15. Alfresco Software has modified source of this file
  16. The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src
  17. ==================================================================== */
  18. package org.apache.poi.ss.usermodel;
  19. import java.math.BigDecimal;
  20. import java.math.RoundingMode;
  21. import java.text.DateFormat;
  22. import java.text.DateFormatSymbols;
  23. import java.text.DecimalFormat;
  24. import java.text.DecimalFormatSymbols;
  25. import java.text.FieldPosition;
  26. import java.text.Format;
  27. import java.text.ParsePosition;
  28. import java.text.SimpleDateFormat;
  29. import java.util.ArrayList;
  30. import java.util.Date;
  31. import java.util.HashMap;
  32. import java.util.Iterator;
  33. import java.util.List;
  34. import java.util.Locale;
  35. import java.util.Map;
  36. import java.util.Observable;
  37. import java.util.Observer;
  38. import java.util.regex.Matcher;
  39. import java.util.regex.Pattern;
  40. import org.apache.poi.ss.format.CellFormat;
  41. import org.apache.poi.ss.format.CellFormatResult;
  42. import org.apache.poi.ss.util.DateFormatConverter;
  43. import org.apache.poi.ss.util.NumberToTextConverter;
  44. import org.apache.poi.util.LocaleUtil;
  45. import org.apache.poi.util.POILogFactory;
  46. import org.apache.poi.util.POILogger;
  47. /**
  48. * DataFormatter contains methods for formatting the value stored in an
  49. * Cell. This can be useful for reports and GUI presentations when you
  50. * need to display data exactly as it appears in Excel. Supported formats
  51. * include currency, SSN, percentages, decimals, dates, phone numbers, zip
  52. * codes, etc.
  53. * <p>
  54. * Internally, formats will be implemented using subclasses of {@link Format}
  55. * such as {@link DecimalFormat} and {@link java.text.SimpleDateFormat}. Therefore the
  56. * formats used by this class must obey the same pattern rules as these Format
  57. * subclasses. This means that only legal number pattern characters ("0", "#",
  58. * ".", "," etc.) may appear in number formats. Other characters can be
  59. * inserted <em>before</em> or <em> after</em> the number pattern to form a
  60. * prefix or suffix.
  61. * </p>
  62. * <p>
  63. * For example the Excel pattern <code>"$#,##0.00 "USD"_);($#,##0.00 "USD")"
  64. * </code> will be correctly formatted as "$1,000.00 USD" or "($1,000.00 USD)".
  65. * However the pattern <code>"00-00-00"</code> is incorrectly formatted by
  66. * DecimalFormat as "000000--". For Excel formats that are not compatible with
  67. * DecimalFormat, you can provide your own custom {@link Format} implementation
  68. * via <code>DataFormatter.addFormat(String,Format)</code>. The following
  69. * custom formats are already provided by this class:
  70. * </p>
  71. * <pre>
  72. * <ul><li>SSN "000-00-0000"</li>
  73. * <li>Phone Number "(###) ###-####"</li>
  74. * <li>Zip plus 4 "00000-0000"</li>
  75. * </ul>
  76. * </pre>
  77. * <p>
  78. * If the Excel format pattern cannot be parsed successfully, then a default
  79. * format will be used. The default number format will mimic the Excel General
  80. * format: "#" for whole numbers and "#.##########" for decimal numbers. You
  81. * can override the default format pattern with <code>
  82. * DataFormatter.setDefaultNumberFormat(Format)</code>. <b>Note:</b> the
  83. * default format will only be used when a Format cannot be created from the
  84. * cell's data format string.
  85. *
  86. * <p>
  87. * Note that by default formatted numeric values are trimmed.
  88. * Excel formats can contain spacers and padding and the default behavior is to strip them off.
  89. * </p>
  90. * <p>Example:</p>
  91. * <p>
  92. * Consider a numeric cell with a value <code>12.343</code> and format <code>"##.##_ "</code>.
  93. * The trailing underscore and space ("_ ") in the format adds a space to the end and Excel formats this cell as <code>"12.34 "</code>,
  94. * but <code>DataFormatter</code> trims the formatted value and returns <code>"12.34"</code>.
  95. * </p>
  96. * You can enable spaces by passing the <code>emulateCsv=true</code> flag in the <code>DateFormatter</code> cosntructor.
  97. * If set to true, then the output tries to conform to what you get when you take an xls or xlsx in Excel and Save As CSV file:
  98. * <ul>
  99. * <li>returned values are not trimmed</li>
  100. * <li>Invalid dates are formatted as 255 pound signs ("#")</li>
  101. * <li>simulate Excel's handling of a format string of all # when the value is 0.
  102. * Excel will output "", <code>DataFormatter</code> will output "0".
  103. * </ul>
  104. * <p>
  105. * Some formats are automatically "localized" by Excel, eg show as mm/dd/yyyy when
  106. * loaded in Excel in some Locales but as dd/mm/yyyy in others. These are always
  107. * returned in the "default" (US) format, as stored in the file.
  108. * Some format strings request an alternate locale, eg
  109. * <code>[$-809]d/m/yy h:mm AM/PM</code> which explicitly requests UK locale.
  110. * These locale directives are (currently) ignored.
  111. * You can use {@link DateFormatConverter} to do some of this localisation if
  112. * you need it.
  113. */
  114. public class DataFormatter implements Observer {
  115. private static final String defaultFractionWholePartFormat = "#";
  116. private static final String defaultFractionFractionPartFormat = "#/##";
  117. /** Pattern to find a number format: "0" or "#" */
  118. private static final Pattern numPattern = Pattern.compile("[0#]+");
  119. /** Pattern to find days of week as text "ddd...." */
  120. private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE);
  121. /** Pattern to find "AM/PM" marker */
  122. private static final Pattern amPmPattern = Pattern.compile("((A|P)[M/P]*)", Pattern.CASE_INSENSITIVE);
  123. /**
  124. * A regex to find locale patterns like [$$-1009] and [$?-452].
  125. * Note that we don't currently process these into locales
  126. */
  127. private static final Pattern localePatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+\\])");
  128. /**
  129. * A regex to match the colour formattings rules.
  130. * Allowed colours are: Black, Blue, Cyan, Green,
  131. * Magenta, Red, White, Yellow, "Color n" (1<=n<=56)
  132. */
  133. private static final Pattern colorPattern =
  134. Pattern.compile("(\\[BLACK\\])|(\\[BLUE\\])|(\\[CYAN\\])|(\\[GREEN\\])|" +
  135. "(\\[MAGENTA\\])|(\\[RED\\])|(\\[WHITE\\])|(\\[YELLOW\\])|" +
  136. "(\\[COLOR\\s*\\d\\])|(\\[COLOR\\s*[0-5]\\d\\])", Pattern.CASE_INSENSITIVE);
  137. /**
  138. * A regex to identify a fraction pattern.
  139. * This requires that replaceAll("\\?", "#") has already been called
  140. */
  141. private static final Pattern fractionPattern = Pattern.compile("(?:([#\\d]+)\\s+)?(#+)\\s*\\/\\s*([#\\d]+)");
  142. /**
  143. * A regex to strip junk out of fraction formats
  144. */
  145. private static final Pattern fractionStripper = Pattern.compile("(\"[^\"]*\")|([^ \\?#\\d\\/]+)");
  146. /**
  147. * A regex to detect if an alternate grouping character is used
  148. * in a numeric format
  149. */
  150. private static final Pattern alternateGrouping = Pattern.compile("([#0]([^.#0])[#0]{3})");
  151. /**
  152. * Cells formatted with a date or time format and which contain invalid date or time values
  153. * show 255 pound signs ("#").
  154. */
  155. private static final String invalidDateTimeString;
  156. static {
  157. StringBuilder buf = new StringBuilder();
  158. for(int i = 0; i < 255; i++) buf.append('#');
  159. invalidDateTimeString = buf.toString();
  160. }
  161. /**
  162. * The decimal symbols of the locale used for formatting values.
  163. */
  164. private DecimalFormatSymbols decimalSymbols;
  165. /**
  166. * The date symbols of the locale used for formatting values.
  167. */
  168. private DateFormatSymbols dateSymbols;
  169. /**
  170. * A default date format, if no date format was given
  171. */
  172. private DateFormat defaultDateformat;
  173. /** <em>General</em> format for numbers. */
  174. private Format generalNumberFormat;
  175. /** A default format to use when a number pattern cannot be parsed. */
  176. private Format defaultNumFormat;
  177. /**
  178. * A map to cache formats.
  179. * Map<String,Format> formats
  180. */
  181. private final Map<String,Format> formats = new HashMap<String,Format>();
  182. private boolean emulateCsv = false;
  183. /** stores the locale valid it the last formatting call */
  184. private Locale locale;
  185. /** stores if the locale should change according to {@link LocaleUtil#getUserLocale()} */
  186. private boolean localeIsAdapting = true;
  187. private class LocaleChangeObservable extends Observable {
  188. void checkForLocaleChange() {
  189. checkForLocaleChange(LocaleUtil.getUserLocale());
  190. }
  191. void checkForLocaleChange(Locale newLocale) {
  192. if (!localeIsAdapting) return;
  193. if (newLocale.equals(locale)) return;
  194. super.setChanged();
  195. notifyObservers(newLocale);
  196. }
  197. }
  198. /** the Observable to notify, when the locale has been changed */
  199. private final LocaleChangeObservable localeChangedObervable = new LocaleChangeObservable();
  200. /** For logging any problems we find */
  201. private static POILogger logger = POILogFactory.getLogger(DataFormatter.class);
  202. /**
  203. * Creates a formatter using the {@link Locale#getDefault() default locale}.
  204. */
  205. public DataFormatter() {
  206. this(false);
  207. this.localeIsAdapting = true;
  208. }
  209. /**
  210. * Creates a formatter using the {@link Locale#getDefault() default locale}.
  211. *
  212. * @param emulateCsv whether to emulate CSV output.
  213. */
  214. public DataFormatter(boolean emulateCsv) {
  215. this(LocaleUtil.getUserLocale(), emulateCsv);
  216. this.localeIsAdapting = true;
  217. }
  218. /**
  219. * Creates a formatter using the given locale.
  220. *
  221. * @param emulateCsv whether to emulate CSV output.
  222. */
  223. public DataFormatter(Locale locale, boolean emulateCsv) {
  224. this(locale);
  225. this.emulateCsv = emulateCsv;
  226. }
  227. /**
  228. * Creates a formatter using the given locale.
  229. */
  230. public DataFormatter(Locale locale) {
  231. localeChangedObervable.addObserver(this);
  232. localeChangedObervable.checkForLocaleChange(locale);
  233. this.localeIsAdapting = false;
  234. }
  235. /**
  236. * Return a Format for the given cell if one exists, otherwise try to
  237. * create one. This method will return <code>null</code> if the any of the
  238. * following is true:
  239. * <ul>
  240. * <li>the cell's style is null</li>
  241. * <li>the style's data format string is null or empty</li>
  242. * <li>the format string cannot be recognized as either a number or date</li>
  243. * </ul>
  244. *
  245. * @param cell The cell to retrieve a Format for
  246. * @return A Format for the format String
  247. */
  248. private Format getFormat(Cell cell) {
  249. if ( cell.getCellStyle() == null) {
  250. return null;
  251. }
  252. int formatIndex = cell.getCellStyle().getDataFormat();
  253. String formatStr = cell.getCellStyle().getDataFormatString();
  254. if(formatStr == null || formatStr.trim().length() == 0) {
  255. return null;
  256. }
  257. return getFormat(cell.getNumericCellValue(), formatIndex, formatStr);
  258. }
  259. private Format getFormat(double cellValue, int formatIndex, String formatStrIn) {
  260. localeChangedObervable.checkForLocaleChange();
  261. // // Might be better to separate out the n p and z formats, falling back to p when n and z are not set.
  262. // // That however would require other code to be re factored.
  263. // String[] formatBits = formatStrIn.split(";");
  264. // int i = cellValue > 0.0 ? 0 : cellValue < 0.0 ? 1 : 2;
  265. // String formatStr = (i < formatBits.length) ? formatBits[i] : formatBits[0];
  266. String formatStr = formatStrIn;
  267. // Excel supports 3+ part conditional data formats, eg positive/negative/zero,
  268. // or (>1000),(>0),(0),(negative). As Java doesn't handle these kinds
  269. // of different formats for different ranges, just +ve/-ve, we need to
  270. // handle these ourselves in a special way.
  271. // For now, if we detect 3+ parts, we call out to CellFormat to handle it
  272. // TODO Going forward, we should really merge the logic between the two classes
  273. if (formatStr.indexOf(";") != -1 &&
  274. formatStr.indexOf(';') != formatStr.lastIndexOf(';')) {
  275. try {
  276. // Ask CellFormat to get a formatter for it
  277. CellFormat cfmt = CellFormat.getInstance(formatStr);
  278. // CellFormat requires callers to identify date vs not, so do so
  279. Object cellValueO = Double.valueOf(cellValue);
  280. if (DateUtil.isADateFormat(formatIndex, formatStr) &&
  281. // don't try to handle Date value 0, let a 3 or 4-part format take care of it
  282. ((Double)cellValueO).doubleValue() != 0.0) {
  283. cellValueO = DateUtil.getJavaDate(cellValue);
  284. }
  285. // Wrap and return (non-cachable - CellFormat does that)
  286. return new CellFormatResultWrapper( cfmt.apply(cellValueO) );
  287. } catch (Exception e) {
  288. logger.log(POILogger.WARN, "Formatting failed for format " + formatStr + ", falling back", e);
  289. }
  290. }
  291. // Excel's # with value 0 will output empty where Java will output 0. This hack removes the # from the format.
  292. if (emulateCsv && cellValue == 0.0 && formatStr.contains("#") && !formatStr.contains("0")) {
  293. formatStr = formatStr.replaceAll("#", "");
  294. }
  295. // See if we already have it cached
  296. Format format = formats.get(formatStr);
  297. if (format != null) {
  298. return format;
  299. }
  300. // Is it one of the special built in types, General or @?
  301. if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) {
  302. return generalNumberFormat;
  303. }
  304. // Build a formatter, and cache it
  305. format = createFormat(cellValue, formatIndex, formatStr);
  306. return format;
  307. }
  308. /**
  309. * Create and return a Format based on the format string from a cell's
  310. * style. If the pattern cannot be parsed, return a default pattern.
  311. *
  312. * @param cell The Excel cell
  313. * @return A Format representing the excel format. May return null.
  314. */
  315. public Format createFormat(Cell cell) {
  316. int formatIndex = cell.getCellStyle().getDataFormat();
  317. String formatStr = cell.getCellStyle().getDataFormatString();
  318. return createFormat(cell.getNumericCellValue(), formatIndex, formatStr);
  319. }
  320. private Format createFormat(double cellValue, int formatIndex, String sFormat) {
  321. localeChangedObervable.checkForLocaleChange();
  322. String formatStr = sFormat;
  323. // Remove colour formatting if present
  324. Matcher colourM = colorPattern.matcher(formatStr);
  325. while(colourM.find()) {
  326. String colour = colourM.group();
  327. // Paranoid replacement...
  328. int at = formatStr.indexOf(colour);
  329. if(at == -1) break;
  330. String nFormatStr = formatStr.substring(0,at) +
  331. formatStr.substring(at+colour.length());
  332. if(nFormatStr.equals(formatStr)) break;
  333. // Try again in case there's multiple
  334. formatStr = nFormatStr;
  335. colourM = colorPattern.matcher(formatStr);
  336. }
  337. // Strip off the locale information, we use an instance-wide locale for everything
  338. Matcher m = localePatternGroup.matcher(formatStr);
  339. while(m.find()) {
  340. String match = m.group();
  341. String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-'));
  342. if (symbol.indexOf('$') > -1) {
  343. StringBuffer sb = new StringBuffer();
  344. sb.append(symbol.substring(0, symbol.indexOf('$')));
  345. sb.append('\\');
  346. sb.append(symbol.substring(symbol.indexOf('$'), symbol.length()));
  347. symbol = sb.toString();
  348. }
  349. formatStr = m.replaceAll(symbol);
  350. m = localePatternGroup.matcher(formatStr);
  351. }
  352. // Check for special cases
  353. if(formatStr == null || formatStr.trim().length() == 0) {
  354. return getDefaultFormat(cellValue);
  355. }
  356. if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) {
  357. return generalNumberFormat;
  358. }
  359. if(DateUtil.isADateFormat(formatIndex,formatStr) &&
  360. DateUtil.isValidExcelDate(cellValue)) {
  361. return createDateFormat(formatStr, cellValue);
  362. }
  363. // Excel supports fractions in format strings, which Java doesn't
  364. if (formatStr.indexOf("#/") >= 0 || formatStr.indexOf("?/") >= 0) {
  365. String[] chunks = formatStr.split(";");
  366. for (int i = 0; i < chunks.length; i++){
  367. String chunk = chunks[i].replaceAll("\\?", "#");
  368. Matcher matcher = fractionStripper.matcher(chunk);
  369. chunk = matcher.replaceAll(" ");
  370. chunk = chunk.replaceAll(" +", " ");
  371. Matcher fractionMatcher = fractionPattern.matcher(chunk);
  372. //take the first match
  373. if (fractionMatcher.find()){
  374. String wholePart = (fractionMatcher.group(1) == null) ? "" : defaultFractionWholePartFormat;
  375. return new FractionFormat(wholePart, fractionMatcher.group(3));
  376. }
  377. }
  378. // Strip custom text in quotes and escaped characters for now as it can cause performance problems in fractions.
  379. //String strippedFormatStr = formatStr.replaceAll("\\\\ ", " ").replaceAll("\\\\.", "").replaceAll("\"[^\"]*\"", " ").replaceAll("\\?", "#");
  380. //System.out.println("formatStr: "+strippedFormatStr);
  381. return new FractionFormat(defaultFractionWholePartFormat, defaultFractionFractionPartFormat);
  382. }
  383. if (numPattern.matcher(formatStr).find()) {
  384. return createNumberFormat(formatStr, cellValue);
  385. }
  386. if (emulateCsv) {
  387. return new ConstantStringFormat(cleanFormatForNumber(formatStr));
  388. }
  389. // TODO - when does this occur?
  390. return null;
  391. }
  392. private Format createDateFormat(String pFormatStr, double cellValue) {
  393. String formatStr = pFormatStr;
  394. formatStr = formatStr.replaceAll("\\\\-","-");
  395. formatStr = formatStr.replaceAll("\\\\,",",");
  396. formatStr = formatStr.replaceAll("\\\\\\.","."); // . is a special regexp char
  397. formatStr = formatStr.replaceAll("\\\\ "," ");
  398. formatStr = formatStr.replaceAll("\\\\/","/"); // weird: m\\/d\\/yyyy
  399. formatStr = formatStr.replaceAll(";@", "");
  400. formatStr = formatStr.replaceAll("\"/\"", "/"); // "/" is escaped for no reason in: mm"/"dd"/"yyyy
  401. formatStr = formatStr.replace("\"\"", "'"); // replace Excel quoting with Java style quoting
  402. formatStr = formatStr.replaceAll("\\\\T","'T'"); // Quote the T is iso8601 style dates
  403. boolean hasAmPm = false;
  404. Matcher amPmMatcher = amPmPattern.matcher(formatStr);
  405. while (amPmMatcher.find()) {
  406. formatStr = amPmMatcher.replaceAll("@");
  407. hasAmPm = true;
  408. amPmMatcher = amPmPattern.matcher(formatStr);
  409. }
  410. formatStr = formatStr.replaceAll("@", "a");
  411. Matcher dateMatcher = daysAsText.matcher(formatStr);
  412. if (dateMatcher.find()) {
  413. String match = dateMatcher.group(0).toUpperCase(Locale.ROOT).replaceAll("D", "E");
  414. formatStr = dateMatcher.replaceAll(match);
  415. }
  416. // Convert excel date format to SimpleDateFormat.
  417. // Excel uses lower and upper case 'm' for both minutes and months.
  418. // From Excel help:
  419. /*
  420. The "m" or "mm" code must appear immediately after the "h" or"hh"
  421. code or immediately before the "ss" code; otherwise, Microsoft
  422. Excel displays the month instead of minutes."
  423. */
  424. StringBuffer sb = new StringBuffer();
  425. char[] chars = formatStr.toCharArray();
  426. boolean mIsMonth = true;
  427. List<Integer> ms = new ArrayList<Integer>();
  428. boolean isElapsed = false;
  429. for(int j=0; j<chars.length; j++) {
  430. char c = chars[j];
  431. if (c == '\'') {
  432. sb.append(c);
  433. j++;
  434. // skip until the next quote
  435. while(j<chars.length) {
  436. c = chars[j];
  437. sb.append(c);
  438. if(c == '\'') {
  439. break;
  440. }
  441. j++;
  442. }
  443. }
  444. else if (c == '[' && !isElapsed) {
  445. isElapsed = true;
  446. mIsMonth = false;
  447. sb.append(c);
  448. }
  449. else if (c == ']' && isElapsed) {
  450. isElapsed = false;
  451. sb.append(c);
  452. }
  453. else if (isElapsed) {
  454. if (c == 'h' || c == 'H') {
  455. sb.append('H');
  456. }
  457. else if (c == 'm' || c == 'M') {
  458. sb.append('m');
  459. }
  460. else if (c == 's' || c == 'S') {
  461. sb.append('s');
  462. }
  463. else {
  464. sb.append(c);
  465. }
  466. }
  467. else if (c == 'h' || c == 'H') {
  468. mIsMonth = false;
  469. if (hasAmPm) {
  470. sb.append('h');
  471. } else {
  472. sb.append('H');
  473. }
  474. }
  475. else if (c == 'm' || c == 'M') {
  476. if(mIsMonth) {
  477. sb.append('M');
  478. ms.add(
  479. Integer.valueOf(sb.length() -1)
  480. );
  481. } else {
  482. sb.append('m');
  483. }
  484. }
  485. else if (c == 's' || c == 'S') {
  486. sb.append('s');
  487. // if 'M' precedes 's' it should be minutes ('m')
  488. for (int i = 0; i < ms.size(); i++) {
  489. int index = ms.get(i).intValue();
  490. if (sb.charAt(index) == 'M') {
  491. sb.replace(index, index+1, "m");
  492. }
  493. }
  494. mIsMonth = true;
  495. ms.clear();
  496. }
  497. else if (Character.isLetter(c)) {
  498. mIsMonth = true;
  499. ms.clear();
  500. if (c == 'y' || c == 'Y') {
  501. sb.append('y');
  502. }
  503. else if (c == 'd' || c == 'D') {
  504. sb.append('d');
  505. }
  506. else {
  507. sb.append(c);
  508. }
  509. }
  510. else {
  511. sb.append(c);
  512. }
  513. }
  514. formatStr = sb.toString();
  515. try {
  516. return new ExcelStyleDateFormatter(formatStr, dateSymbols);
  517. } catch(IllegalArgumentException iae) {
  518. // the pattern could not be parsed correctly,
  519. // so fall back to the default number format
  520. return getDefaultFormat(cellValue);
  521. }
  522. }
  523. private String cleanFormatForNumber(String formatStr) {
  524. StringBuffer sb = new StringBuffer(formatStr);
  525. if (emulateCsv) {
  526. // Requested spacers with "_" are replaced by a single space.
  527. // Full-column-width padding "*" are removed.
  528. // Not processing fractions at this time. Replace ? with space.
  529. // This matches CSV output.
  530. for (int i = 0; i < sb.length(); i++) {
  531. char c = sb.charAt(i);
  532. if (c == '_' || c == '*' || c == '?') {
  533. if (i > 0 && sb.charAt((i - 1)) == '\\') {
  534. // It's escaped, don't worry
  535. continue;
  536. }
  537. if (c == '?') {
  538. sb.setCharAt(i, ' ');
  539. } else if (i < sb.length() - 1) {
  540. // Remove the character we're supposed
  541. // to match the space of / pad to the
  542. // column width with
  543. if (c == '_') {
  544. sb.setCharAt(i + 1, ' ');
  545. } else {
  546. sb.deleteCharAt(i + 1);
  547. }
  548. // Remove the character too
  549. sb.deleteCharAt(i);
  550. i--;
  551. }
  552. }
  553. }
  554. } else {
  555. // If they requested spacers, with "_",
  556. // remove those as we don't do spacing
  557. // If they requested full-column-width
  558. // padding, with "*", remove those too
  559. for (int i = 0; i < sb.length(); i++) {
  560. char c = sb.charAt(i);
  561. if (c == '_' || c == '*') {
  562. if (i > 0 && sb.charAt((i - 1)) == '\\') {
  563. // It's escaped, don't worry
  564. continue;
  565. }
  566. if (i < sb.length() - 1) {
  567. // Remove the character we're supposed
  568. // to match the space of / pad to the
  569. // column width with
  570. sb.deleteCharAt(i + 1);
  571. }
  572. // Remove the _ too
  573. sb.deleteCharAt(i);
  574. i--;
  575. }
  576. }
  577. }
  578. // Now, handle the other aspects like
  579. // quoting and scientific notation
  580. for(int i = 0; i < sb.length(); i++) {
  581. char c = sb.charAt(i);
  582. // remove quotes and back slashes
  583. if (c == '\\' || c == '"') {
  584. sb.deleteCharAt(i);
  585. i--;
  586. // for scientific/engineering notation
  587. } else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') {
  588. sb.deleteCharAt(i);
  589. i--;
  590. }
  591. }
  592. return sb.toString();
  593. }
  594. private Format createNumberFormat(String formatStr, double cellValue) {
  595. String format = cleanFormatForNumber(formatStr);
  596. DecimalFormatSymbols symbols = decimalSymbols;
  597. // Do we need to change the grouping character?
  598. // eg for a format like #'##0 which wants 12'345 not 12,345
  599. Matcher agm = alternateGrouping.matcher(format);
  600. if (agm.find()) {
  601. symbols = DecimalFormatSymbols.getInstance(locale);
  602. char grouping = agm.group(2).charAt(0);
  603. symbols.setGroupingSeparator(grouping);
  604. String oldPart = agm.group(1);
  605. String newPart = oldPart.replace(grouping, ',');
  606. format = format.replace(oldPart, newPart);
  607. }
  608. try {
  609. DecimalFormat df = new DecimalFormat(format, symbols);
  610. setExcelStyleRoundingMode(df);
  611. return df;
  612. } catch(IllegalArgumentException iae) {
  613. // the pattern could not be parsed correctly,
  614. // so fall back to the default number format
  615. return getDefaultFormat(cellValue);
  616. }
  617. }
  618. /**
  619. * Returns a default format for a cell.
  620. * @param cell The cell
  621. * @return a default format
  622. */
  623. public Format getDefaultFormat(Cell cell) {
  624. return getDefaultFormat(cell.getNumericCellValue());
  625. }
  626. private Format getDefaultFormat(double cellValue) {
  627. localeChangedObervable.checkForLocaleChange();
  628. // for numeric cells try user supplied default
  629. if (defaultNumFormat != null) {
  630. return defaultNumFormat;
  631. // otherwise use general format
  632. }
  633. return generalNumberFormat;
  634. }
  635. /**
  636. * Performs Excel-style date formatting, using the
  637. * supplied Date and format
  638. */
  639. private String performDateFormatting(Date d, Format dateFormat) {
  640. return (dateFormat != null ? dateFormat : defaultDateformat).format(d);
  641. }
  642. /**
  643. * Returns the formatted value of an Excel date as a <tt>String</tt> based
  644. * on the cell's <code>DataFormat</code>. i.e. "Thursday, January 02, 2003"
  645. * , "01/02/2003" , "02-Jan" , etc.
  646. *
  647. * @param cell The cell
  648. * @return a formatted date string
  649. */
  650. private String getFormattedDateString(Cell cell) {
  651. Format dateFormat = getFormat(cell);
  652. if(dateFormat instanceof ExcelStyleDateFormatter) {
  653. // Hint about the raw excel value
  654. ((ExcelStyleDateFormatter)dateFormat).setDateToBeFormatted(
  655. cell.getNumericCellValue()
  656. );
  657. }
  658. Date d = cell.getDateCellValue();
  659. return performDateFormatting(d, dateFormat);
  660. }
  661. /**
  662. * Returns the formatted value of an Excel number as a <tt>String</tt>
  663. * based on the cell's <code>DataFormat</code>. Supported formats include
  664. * currency, percents, decimals, phone number, SSN, etc.:
  665. * "61.54%", "$100.00", "(800) 555-1234".
  666. *
  667. * @param cell The cell
  668. * @return a formatted number string
  669. */
  670. private String getFormattedNumberString(Cell cell) {
  671. Format numberFormat = getFormat(cell);
  672. double d = cell.getNumericCellValue();
  673. if (numberFormat == null) {
  674. return String.valueOf(d);
  675. }
  676. String formatted = numberFormat.format(new Double(d));
  677. return formatted.replaceFirst("E(\\d)", "E+$1"); // to match Excel's E-notation
  678. }
  679. /**
  680. * Formats the given raw cell value, based on the supplied
  681. * format index and string, according to excel style rules.
  682. * @see #formatCellValue(Cell)
  683. */
  684. public String formatRawCellContents(double value, int formatIndex, String formatString) {
  685. return formatRawCellContents(value, formatIndex, formatString, false);
  686. }
  687. /**
  688. * Formats the given raw cell value, based on the supplied
  689. * format index and string, according to excel style rules.
  690. * @see #formatCellValue(Cell)
  691. */
  692. public String formatRawCellContents(double value, int formatIndex, String formatString, boolean use1904Windowing) {
  693. localeChangedObervable.checkForLocaleChange();
  694. // Is it a date?
  695. if(DateUtil.isADateFormat(formatIndex,formatString)) {
  696. if(DateUtil.isValidExcelDate(value)) {
  697. Format dateFormat = getFormat(value, formatIndex, formatString);
  698. if(dateFormat instanceof ExcelStyleDateFormatter) {
  699. // Hint about the raw excel value
  700. ((ExcelStyleDateFormatter)dateFormat).setDateToBeFormatted(value);
  701. }
  702. Date d = DateUtil.getJavaDate(value, use1904Windowing);
  703. return performDateFormatting(d, dateFormat);
  704. }
  705. // RK: Invalid dates are 255 #s.
  706. if (emulateCsv) {
  707. return invalidDateTimeString;
  708. }
  709. }
  710. // else Number
  711. Format numberFormat = getFormat(value, formatIndex, formatString);
  712. if (numberFormat == null) {
  713. return String.valueOf(value);
  714. }
  715. // When formatting 'value', double to text to BigDecimal produces more
  716. // accurate results than double to Double in JDK8 (as compared to
  717. // previous versions). However, if the value contains E notation, this
  718. // would expand the values, which we do not want, so revert to
  719. // original method.
  720. String result;
  721. final String textValue = NumberToTextConverter.toText(value);
  722. if (textValue.indexOf('E') > -1) {
  723. result = numberFormat.format(new Double(value));
  724. }
  725. else {
  726. result = numberFormat.format(new BigDecimal(textValue));
  727. }
  728. // Complete scientific notation by adding the missing +.
  729. if (result.indexOf('E') > -1 && !result.contains("E-")) {
  730. result = result.replaceFirst("E", "E+");
  731. }
  732. return result;
  733. }
  734. /**
  735. * <p>
  736. * Returns the formatted value of a cell as a <tt>String</tt> regardless
  737. * of the cell type. If the Excel format pattern cannot be parsed then the
  738. * cell value will be formatted using a default format.
  739. * </p>
  740. * <p>When passed a null or blank cell, this method will return an empty
  741. * String (""). Formulas in formula type cells will not be evaluated.
  742. * </p>
  743. *
  744. * @param cell The cell
  745. * @return the formatted cell value as a String
  746. */
  747. public String formatCellValue(Cell cell) {
  748. return formatCellValue(cell, null);
  749. }
  750. /**
  751. * <p>
  752. * Returns the formatted value of a cell as a <tt>String</tt> regardless
  753. * of the cell type. If the Excel format pattern cannot be parsed then the
  754. * cell value will be formatted using a default format.
  755. * </p>
  756. * <p>When passed a null or blank cell, this method will return an empty
  757. * String (""). Formula cells will be evaluated using the given
  758. * {@link FormulaEvaluator} if the evaluator is non-null. If the
  759. * evaluator is null, then the formula String will be returned. The caller
  760. * is responsible for setting the currentRow on the evaluator
  761. *</p>
  762. *
  763. * @param cell The cell (can be null)
  764. * @param evaluator The FormulaEvaluator (can be null)
  765. * @return a string value of the cell
  766. */
  767. public String formatCellValue(Cell cell, FormulaEvaluator evaluator) {
  768. localeChangedObervable.checkForLocaleChange();
  769. if (cell == null) {
  770. return "";
  771. }
  772. int cellType = cell.getCellType();
  773. if (cellType == Cell.CELL_TYPE_FORMULA) {
  774. if (evaluator == null) {
  775. return cell.getCellFormula();
  776. }
  777. cellType = evaluator.evaluateFormulaCell(cell);
  778. }
  779. switch (cellType) {
  780. case Cell.CELL_TYPE_NUMERIC :
  781. if (DateUtil.isCellDateFormatted(cell)) {
  782. return getFormattedDateString(cell);
  783. }
  784. return getFormattedNumberString(cell);
  785. case Cell.CELL_TYPE_STRING :
  786. return cell.getRichStringCellValue().getString();
  787. case Cell.CELL_TYPE_BOOLEAN :
  788. return String.valueOf(cell.getBooleanCellValue());
  789. case Cell.CELL_TYPE_BLANK :
  790. return "";
  791. case Cell.CELL_TYPE_ERROR:
  792. return FormulaError.forInt(cell.getErrorCellValue()).getString();
  793. }
  794. throw new RuntimeException("Unexpected celltype (" + cellType + ")");
  795. }
  796. /**
  797. * <p>
  798. * Sets a default number format to be used when the Excel format cannot be
  799. * parsed successfully. <b>Note:</b> This is a fall back for when an error
  800. * occurs while parsing an Excel number format pattern. This will not
  801. * affect cells with the <em>General</em> format.
  802. * </p>
  803. * <p>
  804. * The value that will be passed to the Format's format method (specified
  805. * by <code>java.text.Format#format</code>) will be a double value from a
  806. * numeric cell. Therefore the code in the format method should expect a
  807. * <code>Number</code> value.
  808. * </p>
  809. *
  810. * @param format A Format instance to be used as a default
  811. * @see java.text.Format#format
  812. */
  813. public void setDefaultNumberFormat(Format format) {
  814. Iterator<Map.Entry<String,Format>> itr = formats.entrySet().iterator();
  815. while(itr.hasNext()) {
  816. Map.Entry<String,Format> entry = itr.next();
  817. if (entry.getValue() == generalNumberFormat) {
  818. entry.setValue(format);
  819. }
  820. }
  821. defaultNumFormat = format;
  822. }
  823. /**
  824. * Adds a new format to the available formats.
  825. * <p>
  826. * The value that will be passed to the Format's format method (specified
  827. * by <code>java.text.Format#format</code>) will be a double value from a
  828. * numeric cell. Therefore the code in the format method should expect a
  829. * <code>Number</code> value.
  830. * </p>
  831. * @param excelFormatStr The data format string
  832. * @param format A Format instance
  833. */
  834. public void addFormat(String excelFormatStr, Format format) {
  835. formats.put(excelFormatStr, format);
  836. }
  837. // Some custom formats
  838. /**
  839. * @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code>
  840. */
  841. private static DecimalFormat createIntegerOnlyFormat(String fmt) {
  842. DecimalFormatSymbols dsf = DecimalFormatSymbols.getInstance(Locale.ROOT);
  843. DecimalFormat result = new DecimalFormat(fmt, dsf);
  844. result.setParseIntegerOnly(true);
  845. return result;
  846. }
  847. /**
  848. * Enables excel style rounding mode (round half up) on the
  849. * Decimal Format given.
  850. */
  851. public static void setExcelStyleRoundingMode(DecimalFormat format) {
  852. setExcelStyleRoundingMode(format, RoundingMode.HALF_UP);
  853. }
  854. /**
  855. * Enables custom rounding mode on the given Decimal Format.
  856. * @param format DecimalFormat
  857. * @param roundingMode RoundingMode
  858. */
  859. public static void setExcelStyleRoundingMode(DecimalFormat format, RoundingMode roundingMode) {
  860. format.setRoundingMode(roundingMode);
  861. }
  862. /**
  863. * If the Locale has been changed via {@link LocaleUtil#setUserLocale(Locale)} the stored
  864. * formats need to be refreshed. All formats which aren't originated from DataFormatter
  865. * itself, i.e. all Formats added via {@link DataFormatter#addFormat(String, Format)} and
  866. * {@link DataFormatter#setDefaultNumberFormat(Format)}, need to be added again.
  867. * To notify callers, the returned {@link Observable} should be used.
  868. * The Object in {@link Observer#update(Observable, Object)} is the new Locale.
  869. *
  870. * @return the listener object, where callers can register themselves
  871. */
  872. public Observable getLocaleChangedObservable() {
  873. return localeChangedObervable;
  874. }
  875. /**
  876. * Update formats when locale has been changed
  877. *
  878. * @param observable usually this is our own Observable instance
  879. * @param localeObj only reacts on Locale objects
  880. */
  881. public void update(Observable observable, Object localeObj) {
  882. if (!(localeObj instanceof Locale)) return;
  883. Locale newLocale = (Locale)localeObj;
  884. if (!localeIsAdapting || newLocale.equals(locale)) return;
  885. locale = newLocale;
  886. dateSymbols = DateFormatSymbols.getInstance(locale);
  887. decimalSymbols = DecimalFormatSymbols.getInstance(locale);
  888. generalNumberFormat = new ExcelGeneralNumberFormat(locale);
  889. // taken from Date.toString()
  890. defaultDateformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", dateSymbols);
  891. defaultDateformat.setTimeZone(LocaleUtil.getUserTimeZone());
  892. // init built-in formats
  893. formats.clear();
  894. Format zipFormat = ZipPlusFourFormat.instance;
  895. addFormat("00000\\-0000", zipFormat);
  896. addFormat("00000-0000", zipFormat);
  897. Format phoneFormat = PhoneFormat.instance;
  898. // allow for format string variations
  899. addFormat("[<=9999999]###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);
  900. addFormat("[<=9999999]###-####;(###) ###-####", phoneFormat);
  901. addFormat("###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);
  902. addFormat("###-####;(###) ###-####", phoneFormat);
  903. Format ssnFormat = SSNFormat.instance;
  904. addFormat("000\\-00\\-0000", ssnFormat);
  905. addFormat("000-00-0000", ssnFormat);
  906. }
  907. /**
  908. * Format class for Excel's SSN format. This class mimics Excel's built-in
  909. * SSN formatting.
  910. *
  911. * @author James May
  912. */
  913. @SuppressWarnings("serial")
  914. private static final class SSNFormat extends Format {
  915. public static final Format instance = new SSNFormat();
  916. private static final DecimalFormat df = createIntegerOnlyFormat("000000000");
  917. private SSNFormat() {
  918. // enforce singleton
  919. }
  920. /** Format a number as an SSN */
  921. public static String format(Number num) {
  922. String result = df.format(num);
  923. StringBuffer sb = new StringBuffer();
  924. sb.append(result.substring(0, 3)).append('-');
  925. sb.append(result.substring(3, 5)).append('-');
  926. sb.append(result.substring(5, 9));
  927. return sb.toString();
  928. }
  929. @Override
  930. public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
  931. return toAppendTo.append(format((Number)obj));
  932. }
  933. @Override
  934. public Object parseObject(String source, ParsePosition pos) {
  935. return df.parseObject(source, pos);
  936. }
  937. }
  938. /**
  939. * Format class for Excel Zip + 4 format. This class mimics Excel's
  940. * built-in formatting for Zip + 4.
  941. * @author James May
  942. */
  943. @SuppressWarnings("serial")
  944. private static final class ZipPlusFourFormat extends Format {
  945. public static final Format instance = new ZipPlusFourFormat();
  946. private static final DecimalFormat df = createIntegerOnlyFormat("000000000");
  947. private ZipPlusFourFormat() {
  948. // enforce singleton
  949. }
  950. /** Format a number as Zip + 4 */
  951. public static String format(Number num) {
  952. String result = df.format(num);
  953. StringBuffer sb = new StringBuffer();
  954. sb.append(result.substring(0, 5)).append('-');
  955. sb.append(result.substring(5, 9));
  956. return sb.toString();
  957. }
  958. @Override
  959. public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
  960. return toAppendTo.append(format((Number)obj));
  961. }
  962. @Override
  963. public Object parseObject(String source, ParsePosition pos) {
  964. return df.parseObject(source, pos);
  965. }
  966. }
  967. /**
  968. * Format class for Excel phone number format. This class mimics Excel's
  969. * built-in phone number formatting.
  970. * @author James May
  971. */
  972. @SuppressWarnings("serial")
  973. private static final class PhoneFormat extends Format {
  974. public static final Format instance = new PhoneFormat();
  975. private static final DecimalFormat df = createIntegerOnlyFormat("##########");
  976. private PhoneFormat() {
  977. // enforce singleton
  978. }
  979. /** Format a number as a phone number */
  980. public static String format(Number num) {
  981. String result = df.format(num);
  982. StringBuffer sb = new StringBuffer();
  983. String seg1, seg2, seg3;
  984. int len = result.length();
  985. if (len <= 4) {
  986. return result;
  987. }
  988. seg3 = result.substring(len - 4, len);
  989. seg2 = result.substring(Math.max(0, len - 7), len - 4);
  990. seg1 = result.substring(Math.max(0, len - 10), Math.max(0, len - 7));
  991. if(seg1 != null && seg1.trim().length() > 0) {
  992. sb.append('(').append(seg1).append(") ");
  993. }
  994. if(seg2 != null && seg2.trim().length() > 0) {
  995. sb.append(seg2).append('-');
  996. }
  997. sb.append(seg3);
  998. return sb.toString();
  999. }
  1000. @Override
  1001. public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
  1002. return toAppendTo.append(format((Number)obj));
  1003. }
  1004. @Override
  1005. public Object parseObject(String source, ParsePosition pos) {
  1006. return df.parseObject(source, pos);
  1007. }
  1008. }
  1009. /**
  1010. * Format class that does nothing and always returns a constant string.
  1011. *
  1012. * This format is used to simulate Excel's handling of a format string
  1013. * of all # when the value is 0. Excel will output "", Java will output "0".
  1014. *
  1015. * @see DataFormatter#createFormat(double, int, String)
  1016. */
  1017. @SuppressWarnings("serial")
  1018. private static final class ConstantStringFormat extends Format {
  1019. private static final DecimalFormat df = createIntegerOnlyFormat("##########");
  1020. private final String str;
  1021. public ConstantStringFormat(String s) {
  1022. str = s;
  1023. }
  1024. @Override
  1025. public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
  1026. return toAppendTo.append(str);
  1027. }
  1028. @Override
  1029. public Object parseObject(String source, ParsePosition pos) {
  1030. return df.parseObject(source, pos);
  1031. }
  1032. }
  1033. /**
  1034. * Workaround until we merge {@link DataFormatter} with {@link CellFormat}.
  1035. * Constant, non-cachable wrapper around a {@link CellFormatResult}
  1036. */
  1037. @SuppressWarnings("serial")
  1038. private final class CellFormatResultWrapper extends Format {
  1039. private final CellFormatResult result;
  1040. private CellFormatResultWrapper(CellFormatResult result) {
  1041. this.result = result;
  1042. }
  1043. public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
  1044. if (emulateCsv) {
  1045. return toAppendTo.append(result.text);
  1046. } else {
  1047. return toAppendTo.append(result.text.trim());
  1048. }
  1049. }
  1050. public Object parseObject(String source, ParsePosition pos) {
  1051. return null; // Not supported
  1052. }
  1053. }
  1054. }