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

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