NumberFormat.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. class PHPExcel_Style_NumberFormat extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable
  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/y';
  22. const FORMAT_DATE_DMYMINUS = 'd-m-y';
  23. const FORMAT_DATE_DMMINUS = 'd-m';
  24. const FORMAT_DATE_MYMINUS = 'm-y';
  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/y 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 = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  61. /**
  62. * Built-in format Code
  63. *
  64. * @var string
  65. */
  66. protected $builtInFormatCode = 0;
  67. /**
  68. * Create a new PHPExcel_Style_NumberFormat
  69. *
  70. * @param boolean $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 boolean $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 PHPExcel_Style_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. * @return array
  101. */
  102. public function getStyleArray($array)
  103. {
  104. return array('numberformat' => $array);
  105. }
  106. /**
  107. * Apply styles from array
  108. *
  109. * <code>
  110. * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
  111. * array(
  112. * 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
  113. * )
  114. * );
  115. * </code>
  116. *
  117. * @param array $pStyles Array containing style information
  118. * @throws PHPExcel_Exception
  119. * @return PHPExcel_Style_NumberFormat
  120. */
  121. public function applyFromArray($pStyles = null)
  122. {
  123. if (is_array($pStyles)) {
  124. if ($this->isSupervisor) {
  125. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
  126. } else {
  127. if (array_key_exists('code', $pStyles)) {
  128. $this->setFormatCode($pStyles['code']);
  129. }
  130. }
  131. } else {
  132. throw new PHPExcel_Exception("Invalid style array passed.");
  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
  155. * @return PHPExcel_Style_NumberFormat
  156. */
  157. public function setFormatCode($pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL)
  158. {
  159. if ($pValue == '') {
  160. $pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  161. }
  162. if ($this->isSupervisor) {
  163. $styleArray = $this->getStyleArray(array('code' => $pValue));
  164. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  165. } else {
  166. $this->formatCode = $pValue;
  167. $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue);
  168. }
  169. return $this;
  170. }
  171. /**
  172. * Get Built-In Format Code
  173. *
  174. * @return int
  175. */
  176. public function getBuiltInFormatCode()
  177. {
  178. if ($this->isSupervisor) {
  179. return $this->getSharedComponent()->getBuiltInFormatCode();
  180. }
  181. return $this->builtInFormatCode;
  182. }
  183. /**
  184. * Set Built-In Format Code
  185. *
  186. * @param int $pValue
  187. * @return PHPExcel_Style_NumberFormat
  188. */
  189. public function setBuiltInFormatCode($pValue = 0)
  190. {
  191. if ($this->isSupervisor) {
  192. $styleArray = $this->getStyleArray(array('code' => 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 (is_null(self::$builtInFormats)) {
  228. self::$builtInFormats = array();
  229. // General
  230. self::$builtInFormats[0] = PHPExcel_Style_NumberFormat::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. * @return string
  283. */
  284. public static function builtInFormatCode($pIndex)
  285. {
  286. // Clean parameter
  287. $pIndex = intval($pIndex);
  288. // Ensure built-in format codes are available
  289. self::fillBuiltInFormatCodes();
  290. // Lookup format code
  291. if (isset(self::$builtInFormats[$pIndex])) {
  292. return self::$builtInFormats[$pIndex];
  293. }
  294. return '';
  295. }
  296. /**
  297. * Get built-in format code index
  298. *
  299. * @param string $formatCode
  300. * @return int|boolean
  301. */
  302. public static function builtInFormatCodeIndex($formatCode)
  303. {
  304. // Ensure built-in format codes are available
  305. self::fillBuiltInFormatCodes();
  306. // Lookup format code
  307. if (isset(self::$flippedBuiltInFormats[$formatCode])) {
  308. return self::$flippedBuiltInFormats[$formatCode];
  309. }
  310. return false;
  311. }
  312. /**
  313. * Get hash code
  314. *
  315. * @return string Hash code
  316. */
  317. public function getHashCode()
  318. {
  319. if ($this->isSupervisor) {
  320. return $this->getSharedComponent()->getHashCode();
  321. }
  322. return md5(
  323. $this->formatCode .
  324. $this->builtInFormatCode .
  325. __CLASS__
  326. );
  327. }
  328. /**
  329. * Search/replace values to convert Excel date/time format masks to PHP format masks
  330. *
  331. * @var array
  332. */
  333. private static $dateFormatReplacements = array(
  334. // first remove escapes related to non-format characters
  335. '\\' => '',
  336. // 12-hour suffix
  337. 'am/pm' => 'A',
  338. // 4-digit year
  339. 'e' => 'Y',
  340. 'yyyy' => 'Y',
  341. // 2-digit year
  342. 'yy' => 'y',
  343. // first letter of month - no php equivalent
  344. 'mmmmm' => 'M',
  345. // full month name
  346. 'mmmm' => 'F',
  347. // short month name
  348. 'mmm' => 'M',
  349. // mm is minutes if time, but can also be month w/leading zero
  350. // so we try to identify times be the inclusion of a : separator in the mask
  351. // It isn't perfect, but the best way I know how
  352. ':mm' => ':i',
  353. 'mm:' => 'i:',
  354. // month leading zero
  355. 'mm' => 'm',
  356. // month no leading zero
  357. 'm' => 'n',
  358. // full day of week name
  359. 'dddd' => 'l',
  360. // short day of week name
  361. 'ddd' => 'D',
  362. // days leading zero
  363. 'dd' => 'd',
  364. // days no leading zero
  365. 'd' => 'j',
  366. // seconds
  367. 'ss' => 's',
  368. // fractional seconds - no php equivalent
  369. '.s' => ''
  370. );
  371. /**
  372. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock)
  373. *
  374. * @var array
  375. */
  376. private static $dateFormatReplacements24 = array(
  377. 'hh' => 'H',
  378. 'h' => 'G'
  379. );
  380. /**
  381. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock)
  382. *
  383. * @var array
  384. */
  385. private static $dateFormatReplacements12 = array(
  386. 'hh' => 'h',
  387. 'h' => 'g'
  388. );
  389. private static function setLowercaseCallback($matches) {
  390. return mb_strtolower($matches[0]);
  391. }
  392. private static function escapeQuotesCallback($matches) {
  393. return '\\' . implode('\\', str_split($matches[1]));
  394. }
  395. private static function formatAsDate(&$value, &$format)
  396. {
  397. // strip off first part containing e.g. [$-F800] or [$USD-409]
  398. // general syntax: [$<Currency string>-<language info>]
  399. // language info is in hexadecimal
  400. $format = preg_replace('/^(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format);
  401. // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case;
  402. // but we don't want to change any quoted strings
  403. $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', array('self', 'setLowercaseCallback'), $format);
  404. // Only process the non-quoted blocks for date format characters
  405. $blocks = explode('"', $format);
  406. foreach($blocks as $key => &$block) {
  407. if ($key % 2 == 0) {
  408. $block = strtr($block, self::$dateFormatReplacements);
  409. if (!strpos($block, 'A')) {
  410. // 24-hour time format
  411. $block = strtr($block, self::$dateFormatReplacements24);
  412. } else {
  413. // 12-hour time format
  414. $block = strtr($block, self::$dateFormatReplacements12);
  415. }
  416. }
  417. }
  418. $format = implode('"', $blocks);
  419. // escape any quoted characters so that DateTime format() will render them correctly
  420. $format = preg_replace_callback('/"(.*)"/U', array('self', 'escapeQuotesCallback'), $format);
  421. $dateObj = PHPExcel_Shared_Date::ExcelToPHPObject($value);
  422. $value = $dateObj->format($format);
  423. }
  424. private static function formatAsPercentage(&$value, &$format)
  425. {
  426. if ($format === self::FORMAT_PERCENTAGE) {
  427. $value = round((100 * $value), 0) . '%';
  428. } else {
  429. if (preg_match('/\.[#0]+/i', $format, $m)) {
  430. $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1);
  431. $format = str_replace($m[0], $s, $format);
  432. }
  433. if (preg_match('/^[#0]+/', $format, $m)) {
  434. $format = str_replace($m[0], strlen($m[0]), $format);
  435. }
  436. $format = '%' . str_replace('%', 'f%%', $format);
  437. $value = sprintf($format, 100 * $value);
  438. }
  439. }
  440. private static function formatAsFraction(&$value, &$format)
  441. {
  442. $sign = ($value < 0) ? '-' : '';
  443. $integerPart = floor(abs($value));
  444. $decimalPart = trim(fmod(abs($value), 1), '0.');
  445. $decimalLength = strlen($decimalPart);
  446. $decimalDivisor = pow(10, $decimalLength);
  447. $GCD = PHPExcel_Calculation_MathTrig::GCD($decimalPart, $decimalDivisor);
  448. $adjustedDecimalPart = $decimalPart/$GCD;
  449. $adjustedDecimalDivisor = $decimalDivisor/$GCD;
  450. if ((strpos($format, '0') !== false) || (strpos($format, '#') !== false) || (substr($format, 0, 3) == '? ?')) {
  451. if ($integerPart == 0) {
  452. $integerPart = '';
  453. }
  454. $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
  455. } else {
  456. $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
  457. $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
  458. }
  459. }
  460. private static function complexNumberFormatMask($number, $mask, $level = 0)
  461. {
  462. $sign = ($number < 0.0);
  463. $number = abs($number);
  464. if (strpos($mask, '.') !== false) {
  465. $numbers = explode('.', $number . '.0');
  466. $masks = explode('.', $mask . '.0');
  467. $result1 = self::complexNumberFormatMask($numbers[0], $masks[0], 1);
  468. $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), 1));
  469. return (($sign) ? '-' : '') . $result1 . '.' . $result2;
  470. }
  471. $r = preg_match_all('/0+/', $mask, $result, PREG_OFFSET_CAPTURE);
  472. if ($r > 1) {
  473. $result = array_reverse($result[0]);
  474. foreach ($result as $block) {
  475. $divisor = 1 . $block[0];
  476. $size = strlen($block[0]);
  477. $offset = $block[1];
  478. $blockValue = sprintf(
  479. '%0' . $size . 'd',
  480. fmod($number, $divisor)
  481. );
  482. $number = floor($number / $divisor);
  483. $mask = substr_replace($mask, $blockValue, $offset, $size);
  484. }
  485. if ($number > 0) {
  486. $mask = substr_replace($mask, $number, $offset, 0);
  487. }
  488. $result = $mask;
  489. } else {
  490. $result = $number;
  491. }
  492. return (($sign) ? '-' : '') . $result;
  493. }
  494. /**
  495. * Convert a value in a pre-defined format to a PHP string
  496. *
  497. * @param mixed $value Value to format
  498. * @param string $format Format code
  499. * @param array $callBack Callback function for additional formatting of string
  500. * @return string Formatted string
  501. */
  502. public static function toFormattedString($value = '0', $format = PHPExcel_Style_NumberFormat::FORMAT_GENERAL, $callBack = null)
  503. {
  504. // For now we do not treat strings although section 4 of a format code affects strings
  505. if (!is_numeric($value)) {
  506. return $value;
  507. }
  508. // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
  509. // it seems to round numbers to a total of 10 digits.
  510. if (($format === PHPExcel_Style_NumberFormat::FORMAT_GENERAL) || ($format === PHPExcel_Style_NumberFormat::FORMAT_TEXT)) {
  511. return $value;
  512. }
  513. // Convert any other escaped characters to quoted strings, e.g. (\T to "T")
  514. $format = preg_replace('/(\\\(.))(?=(?:[^"]|"[^"]*")*$)/u', '"${2}"', $format);
  515. // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal)
  516. $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format);
  517. // Extract the relevant section depending on whether number is positive, negative, or zero?
  518. // Text not supported yet.
  519. // Here is how the sections apply to various values in Excel:
  520. // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
  521. // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
  522. // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
  523. // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
  524. switch (count($sections)) {
  525. case 1:
  526. $format = $sections[0];
  527. break;
  528. case 2:
  529. $format = ($value >= 0) ? $sections[0] : $sections[1];
  530. $value = abs($value); // Use the absolute value
  531. break;
  532. case 3:
  533. $format = ($value > 0) ?
  534. $sections[0] : ( ($value < 0) ?
  535. $sections[1] : $sections[2]);
  536. $value = abs($value); // Use the absolute value
  537. break;
  538. case 4:
  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. default:
  545. // something is wrong, just use first section
  546. $format = $sections[0];
  547. break;
  548. }
  549. // In Excel formats, "_" is used to add spacing,
  550. // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space
  551. $format = preg_replace('/_./', ' ', $format);
  552. // Save format with color information for later use below
  553. $formatColor = $format;
  554. // Strip color information
  555. $color_regex = '/^\\[[a-zA-Z]+\\]/';
  556. $format = preg_replace($color_regex, '', $format);
  557. // Let's begin inspecting the format and converting the value to a formatted string
  558. // Check for date/time characters (not inside quotes)
  559. if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) {
  560. // datetime format
  561. self::formatAsDate($value, $format);
  562. } elseif (preg_match('/%$/', $format)) {
  563. // % number format
  564. self::formatAsPercentage($value, $format);
  565. } else {
  566. if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) {
  567. $value = 'EUR ' . sprintf('%1.2f', $value);
  568. } else {
  569. // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
  570. $format = str_replace(array('"', '*'), '', $format);
  571. // Find out if we need thousands separator
  572. // This is indicated by a comma enclosed by a digit placeholder:
  573. // #,# or 0,0
  574. $useThousands = preg_match('/(#,#|0,0)/', $format);
  575. if ($useThousands) {
  576. $format = preg_replace('/0,0/', '00', $format);
  577. $format = preg_replace('/#,#/', '##', $format);
  578. }
  579. // Scale thousands, millions,...
  580. // This is indicated by a number of commas after a digit placeholder:
  581. // #, or 0.0,,
  582. $scale = 1; // same as no scale
  583. $matches = array();
  584. if (preg_match('/(#|0)(,+)/', $format, $matches)) {
  585. $scale = pow(1000, strlen($matches[2]));
  586. // strip the commas
  587. $format = preg_replace('/0,+/', '0', $format);
  588. $format = preg_replace('/#,+/', '#', $format);
  589. }
  590. if (preg_match('/#?.*\?\/\?/', $format, $m)) {
  591. //echo 'Format mask is fractional '.$format.' <br />';
  592. if ($value != (int)$value) {
  593. self::formatAsFraction($value, $format);
  594. }
  595. } else {
  596. // Handle the number itself
  597. // scale number
  598. $value = $value / $scale;
  599. // Strip #
  600. $format = preg_replace('/\\#/', '0', $format);
  601. $n = "/\[[^\]]+\]/";
  602. $m = preg_replace($n, '', $format);
  603. $number_regex = "/(0+)(\.?)(0*)/";
  604. if (preg_match($number_regex, $m, $matches)) {
  605. $left = $matches[1];
  606. $dec = $matches[2];
  607. $right = $matches[3];
  608. // minimun width of formatted number (including dot)
  609. $minWidth = strlen($left) + strlen($dec) + strlen($right);
  610. if ($useThousands) {
  611. $value = number_format(
  612. $value,
  613. strlen($right),
  614. PHPExcel_Shared_String::getDecimalSeparator(),
  615. PHPExcel_Shared_String::getThousandsSeparator()
  616. );
  617. $value = preg_replace($number_regex, $value, $format);
  618. } else {
  619. if (preg_match('/[0#]E[+-]0/i', $format)) {
  620. // Scientific format
  621. $value = sprintf('%5.2E', $value);
  622. } elseif (preg_match('/0([^\d\.]+)0/', $format)) {
  623. $value = self::complexNumberFormatMask($value, $format);
  624. } else {
  625. $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
  626. $value = sprintf($sprintf_pattern, $value);
  627. $value = preg_replace($number_regex, $value, $format);
  628. }
  629. }
  630. }
  631. }
  632. if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
  633. // Currency or Accounting
  634. $currencyFormat = $m[0];
  635. $currencyCode = $m[1];
  636. list($currencyCode) = explode('-', $currencyCode);
  637. if ($currencyCode == '') {
  638. $currencyCode = PHPExcel_Shared_String::getCurrencyCode();
  639. }
  640. $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value);
  641. }
  642. }
  643. }
  644. // Escape any escaped slashes to a single slash
  645. $format = preg_replace("/\\\\/u", '\\', $format);
  646. // Additional formatting provided by callback function
  647. if ($callBack !== null) {
  648. list($writerInstance, $function) = $callBack;
  649. $value = $writerInstance->$function($value, $formatColor);
  650. }
  651. return $value;
  652. }
  653. }