NumberFormat.php 27 KB

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