No Description

NumberFormat.php 21KB

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