NumberFormat.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Style;
  3. use PhpOffice\PhpSpreadsheet\Calculation\MathTrig;
  4. use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
  5. use PhpOffice\PhpSpreadsheet\Shared\Date;
  6. use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
  7. class NumberFormat extends Supervisor
  8. {
  9. // Pre-defined formats
  10. const FORMAT_GENERAL = 'General';
  11. const FORMAT_TEXT = '@';
  12. const FORMAT_NUMBER = '0';
  13. const FORMAT_NUMBER_00 = '0.00';
  14. const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
  15. const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
  16. const FORMAT_PERCENTAGE = '0%';
  17. const FORMAT_PERCENTAGE_00 = '0.00%';
  18. const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
  19. const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
  20. const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
  21. const FORMAT_DATE_DMYSLASH = 'd/m/yy';
  22. const FORMAT_DATE_DMYMINUS = 'd-m-yy';
  23. const FORMAT_DATE_DMMINUS = 'd-m';
  24. const FORMAT_DATE_MYMINUS = 'm-yy';
  25. const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
  26. const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
  27. const FORMAT_DATE_XLSX16 = 'd-mmm';
  28. const FORMAT_DATE_XLSX17 = 'mmm-yy';
  29. const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
  30. const FORMAT_DATE_DATETIME = 'd/m/yy h:mm';
  31. const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
  32. const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
  33. const FORMAT_DATE_TIME3 = 'h:mm';
  34. const FORMAT_DATE_TIME4 = 'h:mm:ss';
  35. const FORMAT_DATE_TIME5 = 'mm:ss';
  36. const FORMAT_DATE_TIME6 = 'h:mm:ss';
  37. const FORMAT_DATE_TIME7 = 'i:s.S';
  38. const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
  39. const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
  40. const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
  41. const FORMAT_CURRENCY_USD = '$#,##0_-';
  42. const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-';
  43. /**
  44. * Excel built-in number formats.
  45. *
  46. * @var array
  47. */
  48. protected static $builtInFormats;
  49. /**
  50. * Excel built-in number formats (flipped, for faster lookups).
  51. *
  52. * @var array
  53. */
  54. protected static $flippedBuiltInFormats;
  55. /**
  56. * Format Code.
  57. *
  58. * @var string
  59. */
  60. protected $formatCode = self::FORMAT_GENERAL;
  61. /**
  62. * Built-in format Code.
  63. *
  64. * @var string
  65. */
  66. protected $builtInFormatCode = 0;
  67. /**
  68. * Create a new NumberFormat.
  69. *
  70. * @param bool $isSupervisor Flag indicating if this is a supervisor or not
  71. * Leave this value at default unless you understand exactly what
  72. * its ramifications are
  73. * @param bool $isConditional Flag indicating if this is a conditional style or not
  74. * Leave this value at default unless you understand exactly what
  75. * its ramifications are
  76. */
  77. public function __construct($isSupervisor = false, $isConditional = false)
  78. {
  79. // Supervisor?
  80. parent::__construct($isSupervisor);
  81. if ($isConditional) {
  82. $this->formatCode = null;
  83. $this->builtInFormatCode = false;
  84. }
  85. }
  86. /**
  87. * Get the shared style component for the currently active cell in currently active sheet.
  88. * Only used for style supervisor.
  89. *
  90. * @return NumberFormat
  91. */
  92. public function getSharedComponent()
  93. {
  94. return $this->parent->getSharedComponent()->getNumberFormat();
  95. }
  96. /**
  97. * Build style array from subcomponents.
  98. *
  99. * @param array $array
  100. *
  101. * @return array
  102. */
  103. public function getStyleArray($array)
  104. {
  105. return ['numberFormat' => $array];
  106. }
  107. /**
  108. * Apply styles from array.
  109. * <code>
  110. * $spreadsheet->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
  111. * array(
  112. * 'formatCode' => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
  113. * )
  114. * );
  115. * </code>.
  116. *
  117. * @param array $pStyles Array containing style information
  118. *
  119. * @throws PhpSpreadsheetException
  120. *
  121. * @return NumberFormat
  122. */
  123. public function applyFromArray(array $pStyles)
  124. {
  125. if ($this->isSupervisor) {
  126. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
  127. } else {
  128. if (isset($pStyles['formatCode'])) {
  129. $this->setFormatCode($pStyles['formatCode']);
  130. }
  131. }
  132. return $this;
  133. }
  134. /**
  135. * Get Format Code.
  136. *
  137. * @return string
  138. */
  139. public function getFormatCode()
  140. {
  141. if ($this->isSupervisor) {
  142. return $this->getSharedComponent()->getFormatCode();
  143. }
  144. if ($this->builtInFormatCode !== false) {
  145. return self::builtInFormatCode($this->builtInFormatCode);
  146. }
  147. return $this->formatCode;
  148. }
  149. /**
  150. * Set Format Code.
  151. *
  152. * @param string $pValue see self::FORMAT_*
  153. *
  154. * @return NumberFormat
  155. */
  156. public function setFormatCode($pValue)
  157. {
  158. if ($pValue == '') {
  159. $pValue = self::FORMAT_GENERAL;
  160. }
  161. if ($this->isSupervisor) {
  162. $styleArray = $this->getStyleArray(['formatCode' => $pValue]);
  163. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  164. } else {
  165. $this->formatCode = $pValue;
  166. $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue);
  167. }
  168. return $this;
  169. }
  170. /**
  171. * Get Built-In Format Code.
  172. *
  173. * @return int
  174. */
  175. public function getBuiltInFormatCode()
  176. {
  177. if ($this->isSupervisor) {
  178. return $this->getSharedComponent()->getBuiltInFormatCode();
  179. }
  180. return $this->builtInFormatCode;
  181. }
  182. /**
  183. * Set Built-In Format Code.
  184. *
  185. * @param int $pValue
  186. *
  187. * @return NumberFormat
  188. */
  189. public function setBuiltInFormatCode($pValue)
  190. {
  191. if ($this->isSupervisor) {
  192. $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($pValue)]);
  193. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  194. } else {
  195. $this->builtInFormatCode = $pValue;
  196. $this->formatCode = self::builtInFormatCode($pValue);
  197. }
  198. return $this;
  199. }
  200. /**
  201. * Fill built-in format codes.
  202. */
  203. private static function fillBuiltInFormatCodes()
  204. {
  205. // [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance]
  206. // 18.8.30. numFmt (Number Format)
  207. //
  208. // The ECMA standard defines built-in format IDs
  209. // 14: "mm-dd-yy"
  210. // 22: "m/d/yy h:mm"
  211. // 37: "#,##0 ;(#,##0)"
  212. // 38: "#,##0 ;[Red](#,##0)"
  213. // 39: "#,##0.00;(#,##0.00)"
  214. // 40: "#,##0.00;[Red](#,##0.00)"
  215. // 47: "mmss.0"
  216. // KOR fmt 55: "yyyy-mm-dd"
  217. // Excel defines built-in format IDs
  218. // 14: "m/d/yyyy"
  219. // 22: "m/d/yyyy h:mm"
  220. // 37: "#,##0_);(#,##0)"
  221. // 38: "#,##0_);[Red](#,##0)"
  222. // 39: "#,##0.00_);(#,##0.00)"
  223. // 40: "#,##0.00_);[Red](#,##0.00)"
  224. // 47: "mm:ss.0"
  225. // KOR fmt 55: "yyyy/mm/dd"
  226. // Built-in format codes
  227. if (self::$builtInFormats === null) {
  228. self::$builtInFormats = [];
  229. // General
  230. self::$builtInFormats[0] = self::FORMAT_GENERAL;
  231. self::$builtInFormats[1] = '0';
  232. self::$builtInFormats[2] = '0.00';
  233. self::$builtInFormats[3] = '#,##0';
  234. self::$builtInFormats[4] = '#,##0.00';
  235. self::$builtInFormats[9] = '0%';
  236. self::$builtInFormats[10] = '0.00%';
  237. self::$builtInFormats[11] = '0.00E+00';
  238. self::$builtInFormats[12] = '# ?/?';
  239. self::$builtInFormats[13] = '# ??/??';
  240. self::$builtInFormats[14] = 'm/d/yyyy'; // Despite ECMA 'mm-dd-yy';
  241. self::$builtInFormats[15] = 'd-mmm-yy';
  242. self::$builtInFormats[16] = 'd-mmm';
  243. self::$builtInFormats[17] = 'mmm-yy';
  244. self::$builtInFormats[18] = 'h:mm AM/PM';
  245. self::$builtInFormats[19] = 'h:mm:ss AM/PM';
  246. self::$builtInFormats[20] = 'h:mm';
  247. self::$builtInFormats[21] = 'h:mm:ss';
  248. self::$builtInFormats[22] = 'm/d/yyyy h:mm'; // Despite ECMA 'm/d/yy h:mm';
  249. self::$builtInFormats[37] = '#,##0_);(#,##0)'; // Despite ECMA '#,##0 ;(#,##0)';
  250. self::$builtInFormats[38] = '#,##0_);[Red](#,##0)'; // Despite ECMA '#,##0 ;[Red](#,##0)';
  251. self::$builtInFormats[39] = '#,##0.00_);(#,##0.00)'; // Despite ECMA '#,##0.00;(#,##0.00)';
  252. self::$builtInFormats[40] = '#,##0.00_);[Red](#,##0.00)'; // Despite ECMA '#,##0.00;[Red](#,##0.00)';
  253. self::$builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
  254. self::$builtInFormats[45] = 'mm:ss';
  255. self::$builtInFormats[46] = '[h]:mm:ss';
  256. self::$builtInFormats[47] = 'mm:ss.0'; // Despite ECMA 'mmss.0';
  257. self::$builtInFormats[48] = '##0.0E+0';
  258. self::$builtInFormats[49] = '@';
  259. // CHT
  260. self::$builtInFormats[27] = '[$-404]e/m/d';
  261. self::$builtInFormats[30] = 'm/d/yy';
  262. self::$builtInFormats[36] = '[$-404]e/m/d';
  263. self::$builtInFormats[50] = '[$-404]e/m/d';
  264. self::$builtInFormats[57] = '[$-404]e/m/d';
  265. // THA
  266. self::$builtInFormats[59] = 't0';
  267. self::$builtInFormats[60] = 't0.00';
  268. self::$builtInFormats[61] = 't#,##0';
  269. self::$builtInFormats[62] = 't#,##0.00';
  270. self::$builtInFormats[67] = 't0%';
  271. self::$builtInFormats[68] = 't0.00%';
  272. self::$builtInFormats[69] = 't# ?/?';
  273. self::$builtInFormats[70] = 't# ??/??';
  274. // Flip array (for faster lookups)
  275. self::$flippedBuiltInFormats = array_flip(self::$builtInFormats);
  276. }
  277. }
  278. /**
  279. * Get built-in format code.
  280. *
  281. * @param int $pIndex
  282. *
  283. * @return string
  284. */
  285. public static function builtInFormatCode($pIndex)
  286. {
  287. // Clean parameter
  288. $pIndex = (int) $pIndex;
  289. // Ensure built-in format codes are available
  290. self::fillBuiltInFormatCodes();
  291. // Lookup format code
  292. if (isset(self::$builtInFormats[$pIndex])) {
  293. return self::$builtInFormats[$pIndex];
  294. }
  295. return '';
  296. }
  297. /**
  298. * Get built-in format code index.
  299. *
  300. * @param string $formatCode
  301. *
  302. * @return bool|int
  303. */
  304. public static function builtInFormatCodeIndex($formatCode)
  305. {
  306. // Ensure built-in format codes are available
  307. self::fillBuiltInFormatCodes();
  308. // Lookup format code
  309. if (isset(self::$flippedBuiltInFormats[$formatCode])) {
  310. return self::$flippedBuiltInFormats[$formatCode];
  311. }
  312. return false;
  313. }
  314. /**
  315. * Get hash code.
  316. *
  317. * @return string Hash code
  318. */
  319. public function getHashCode()
  320. {
  321. if ($this->isSupervisor) {
  322. return $this->getSharedComponent()->getHashCode();
  323. }
  324. return md5(
  325. $this->formatCode .
  326. $this->builtInFormatCode .
  327. __CLASS__
  328. );
  329. }
  330. /**
  331. * Search/replace values to convert Excel date/time format masks to PHP format masks.
  332. *
  333. * @var array
  334. */
  335. private static $dateFormatReplacements = [
  336. // first remove escapes related to non-format characters
  337. '\\' => '',
  338. // 12-hour suffix
  339. 'am/pm' => 'A',
  340. // 4-digit year
  341. 'e' => 'Y',
  342. 'yyyy' => 'Y',
  343. // 2-digit year
  344. 'yy' => 'y',
  345. // first letter of month - no php equivalent
  346. 'mmmmm' => 'M',
  347. // full month name
  348. 'mmmm' => 'F',
  349. // short month name
  350. 'mmm' => 'M',
  351. // mm is minutes if time, but can also be month w/leading zero
  352. // so we try to identify times be the inclusion of a : separator in the mask
  353. // It isn't perfect, but the best way I know how
  354. ':mm' => ':i',
  355. 'mm:' => 'i:',
  356. // month leading zero
  357. 'mm' => 'm',
  358. // month no leading zero
  359. 'm' => 'n',
  360. // full day of week name
  361. 'dddd' => 'l',
  362. // short day of week name
  363. 'ddd' => 'D',
  364. // days leading zero
  365. 'dd' => 'd',
  366. // days no leading zero
  367. 'd' => 'j',
  368. // seconds
  369. 'ss' => 's',
  370. // fractional seconds - no php equivalent
  371. '.s' => '',
  372. ];
  373. /**
  374. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock).
  375. *
  376. * @var array
  377. */
  378. private static $dateFormatReplacements24 = [
  379. 'hh' => 'H',
  380. 'h' => 'G',
  381. ];
  382. /**
  383. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock).
  384. *
  385. * @var array
  386. */
  387. private static $dateFormatReplacements12 = [
  388. 'hh' => 'h',
  389. 'h' => 'g',
  390. ];
  391. private static function setLowercaseCallback($matches)
  392. {
  393. return mb_strtolower($matches[0]);
  394. }
  395. private static function escapeQuotesCallback($matches)
  396. {
  397. return '\\' . implode('\\', str_split($matches[1]));
  398. }
  399. private static function formatAsDate(&$value, &$format)
  400. {
  401. // strip off first part containing e.g. [$-F800] or [$USD-409]
  402. // general syntax: [$<Currency string>-<language info>]
  403. // language info is in hexadecimal
  404. // strip off chinese part like [DBNum1][$-804]
  405. $format = preg_replace('/^(\[[0-9A-Za-z]*\])*(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format);
  406. // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case;
  407. // but we don't want to change any quoted strings
  408. $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', ['self', 'setLowercaseCallback'], $format);
  409. // Only process the non-quoted blocks for date format characters
  410. $blocks = explode('"', $format);
  411. foreach ($blocks as $key => &$block) {
  412. if ($key % 2 == 0) {
  413. $block = strtr($block, self::$dateFormatReplacements);
  414. if (!strpos($block, 'A')) {
  415. // 24-hour time format
  416. $block = strtr($block, self::$dateFormatReplacements24);
  417. } else {
  418. // 12-hour time format
  419. $block = strtr($block, self::$dateFormatReplacements12);
  420. }
  421. }
  422. }
  423. $format = implode('"', $blocks);
  424. // escape any quoted characters so that DateTime format() will render them correctly
  425. $format = preg_replace_callback('/"(.*)"/U', ['self', 'escapeQuotesCallback'], $format);
  426. $dateObj = Date::excelToDateTimeObject($value);
  427. $value = $dateObj->format($format);
  428. }
  429. private static function formatAsPercentage(&$value, &$format)
  430. {
  431. if ($format === self::FORMAT_PERCENTAGE) {
  432. $value = round((100 * $value), 0) . '%';
  433. } else {
  434. if (preg_match('/\.[#0]+/', $format, $m)) {
  435. $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1);
  436. $format = str_replace($m[0], $s, $format);
  437. }
  438. if (preg_match('/^[#0]+/', $format, $m)) {
  439. $format = str_replace($m[0], strlen($m[0]), $format);
  440. }
  441. $format = '%' . str_replace('%', 'f%%', $format);
  442. $value = sprintf($format, 100 * $value);
  443. }
  444. }
  445. private static function formatAsFraction(&$value, &$format)
  446. {
  447. $sign = ($value < 0) ? '-' : '';
  448. $integerPart = floor(abs($value));
  449. $decimalPart = trim(fmod(abs($value), 1), '0.');
  450. $decimalLength = strlen($decimalPart);
  451. $decimalDivisor = pow(10, $decimalLength);
  452. $GCD = MathTrig::GCD($decimalPart, $decimalDivisor);
  453. $adjustedDecimalPart = $decimalPart / $GCD;
  454. $adjustedDecimalDivisor = $decimalDivisor / $GCD;
  455. if ((strpos($format, '0') !== false) || (strpos($format, '#') !== false) || (substr($format, 0, 3) == '? ?')) {
  456. if ($integerPart == 0) {
  457. $integerPart = '';
  458. }
  459. $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
  460. } else {
  461. $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
  462. $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
  463. }
  464. }
  465. private static function complexNumberFormatMask($number, $mask)
  466. {
  467. $sign = ($number < 0.0);
  468. $number = abs($number);
  469. if (strpos($mask, '.') !== false) {
  470. $numbers = explode('.', $number . '.0');
  471. $masks = explode('.', $mask . '.0');
  472. $result1 = self::complexNumberFormatMask($numbers[0], $masks[0]);
  473. $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1])));
  474. return (($sign) ? '-' : '') . $result1 . '.' . $result2;
  475. }
  476. $r = preg_match_all('/0+/', $mask, $result, PREG_OFFSET_CAPTURE);
  477. if ($r > 1) {
  478. $result = array_reverse($result[0]);
  479. foreach ($result as $block) {
  480. $divisor = 1 . $block[0];
  481. $size = strlen($block[0]);
  482. $offset = $block[1];
  483. $blockValue = sprintf(
  484. '%0' . $size . 'd',
  485. fmod($number, $divisor)
  486. );
  487. $number = floor($number / $divisor);
  488. $mask = substr_replace($mask, $blockValue, $offset, $size);
  489. }
  490. if ($number > 0) {
  491. $mask = substr_replace($mask, $number, $offset, 0);
  492. }
  493. $result = $mask;
  494. } else {
  495. $result = $number;
  496. }
  497. return (($sign) ? '-' : '') . $result;
  498. }
  499. /**
  500. * Convert a value in a pre-defined format to a PHP string.
  501. *
  502. * @param mixed $value Value to format
  503. * @param string $format Format code, see = self::FORMAT_*
  504. * @param array $callBack Callback function for additional formatting of string
  505. *
  506. * @return string Formatted string
  507. */
  508. public static function toFormattedString($value, $format, $callBack = null)
  509. {
  510. // For now we do not treat strings although section 4 of a format code affects strings
  511. if (!is_numeric($value)) {
  512. return $value;
  513. }
  514. // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
  515. // it seems to round numbers to a total of 10 digits.
  516. if (($format === self::FORMAT_GENERAL) || ($format === self::FORMAT_TEXT)) {
  517. return $value;
  518. }
  519. // Convert any other escaped characters to quoted strings, e.g. (\T to "T")
  520. $format = preg_replace('/(\\\(.))(?=(?:[^"]|"[^"]*")*$)/u', '"${2}"', $format);
  521. // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal)
  522. $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format);
  523. // Extract the relevant section depending on whether number is positive, negative, or zero?
  524. // Text not supported yet.
  525. // Here is how the sections apply to various values in Excel:
  526. // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
  527. // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
  528. // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
  529. // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
  530. switch (count($sections)) {
  531. case 1:
  532. $format = $sections[0];
  533. break;
  534. case 2:
  535. $format = ($value >= 0) ? $sections[0] : $sections[1];
  536. $value = abs($value); // Use the absolute value
  537. break;
  538. case 3:
  539. $format = ($value > 0) ?
  540. $sections[0] : (($value < 0) ?
  541. $sections[1] : $sections[2]);
  542. $value = abs($value); // Use the absolute value
  543. break;
  544. case 4:
  545. $format = ($value > 0) ?
  546. $sections[0] : (($value < 0) ?
  547. $sections[1] : $sections[2]);
  548. $value = abs($value); // Use the absolute value
  549. break;
  550. default:
  551. // something is wrong, just use first section
  552. $format = $sections[0];
  553. break;
  554. }
  555. // In Excel formats, "_" is used to add spacing,
  556. // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space
  557. $format = preg_replace('/_./', ' ', $format);
  558. // Save format with color information for later use below
  559. $formatColor = $format;
  560. // Strip color information
  561. $color_regex = '/^\\[[a-zA-Z]+\\]/';
  562. $format = preg_replace($color_regex, '', $format);
  563. // Let's begin inspecting the format and converting the value to a formatted string
  564. // Check for date/time characters (not inside quotes)
  565. if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) {
  566. // datetime format
  567. self::formatAsDate($value, $format);
  568. } elseif (preg_match('/%$/', $format)) {
  569. // % number format
  570. self::formatAsPercentage($value, $format);
  571. } else {
  572. if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) {
  573. $value = 'EUR ' . sprintf('%1.2f', $value);
  574. } else {
  575. // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
  576. $format = str_replace(['"', '*'], '', $format);
  577. // Find out if we need thousands separator
  578. // This is indicated by a comma enclosed by a digit placeholder:
  579. // #,# or 0,0
  580. $useThousands = preg_match('/(#,#|0,0)/', $format);
  581. if ($useThousands) {
  582. $format = preg_replace('/0,0/', '00', $format);
  583. $format = preg_replace('/#,#/', '##', $format);
  584. }
  585. // Scale thousands, millions,...
  586. // This is indicated by a number of commas after a digit placeholder:
  587. // #, or 0.0,,
  588. $scale = 1; // same as no scale
  589. $matches = [];
  590. if (preg_match('/(#|0)(,+)/', $format, $matches)) {
  591. $scale = pow(1000, strlen($matches[2]));
  592. // strip the commas
  593. $format = preg_replace('/0,+/', '0', $format);
  594. $format = preg_replace('/#,+/', '#', $format);
  595. }
  596. if (preg_match('/#?.*\?\/\?/', $format, $m)) {
  597. if ($value != (int) $value) {
  598. self::formatAsFraction($value, $format);
  599. }
  600. } else {
  601. // Handle the number itself
  602. // scale number
  603. $value = $value / $scale;
  604. // Strip #
  605. $format = preg_replace('/\\#/', '0', $format);
  606. $n = '/\\[[^\\]]+\\]/';
  607. $m = preg_replace($n, '', $format);
  608. $number_regex = '/(0+)(\\.?)(0*)/';
  609. if (preg_match($number_regex, $m, $matches)) {
  610. $left = $matches[1];
  611. $dec = $matches[2];
  612. $right = $matches[3];
  613. // minimun width of formatted number (including dot)
  614. $minWidth = strlen($left) + strlen($dec) + strlen($right);
  615. if ($useThousands) {
  616. $value = number_format(
  617. $value,
  618. strlen($right),
  619. StringHelper::getDecimalSeparator(),
  620. StringHelper::getThousandsSeparator()
  621. );
  622. $value = preg_replace($number_regex, $value, $format);
  623. } else {
  624. if (preg_match('/[0#]E[+-]0/i', $format)) {
  625. // Scientific format
  626. $value = sprintf('%5.2E', $value);
  627. } elseif (preg_match('/0([^\d\.]+)0/', $format)) {
  628. $value = self::complexNumberFormatMask($value, $format);
  629. } else {
  630. $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f';
  631. $value = sprintf($sprintf_pattern, $value);
  632. $value = preg_replace($number_regex, $value, $format);
  633. }
  634. }
  635. }
  636. }
  637. if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
  638. // Currency or Accounting
  639. $currencyCode = $m[1];
  640. list($currencyCode) = explode('-', $currencyCode);
  641. if ($currencyCode == '') {
  642. $currencyCode = StringHelper::getCurrencyCode();
  643. }
  644. $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value);
  645. }
  646. }
  647. }
  648. // Additional formatting provided by callback function
  649. if ($callBack !== null) {
  650. list($writerInstance, $function) = $callBack;
  651. $value = $writerInstance->$function($value, $formatColor);
  652. }
  653. return $value;
  654. }
  655. }