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

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