NumberFormat.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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 1.8.0, 2014-03-02
  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. }
  111. }
  112. /**
  113. * Get the shared style component for the currently active cell in currently active sheet.
  114. * Only used for style supervisor
  115. *
  116. * @return PHPExcel_Style_NumberFormat
  117. */
  118. public function getSharedComponent()
  119. {
  120. return $this->_parent->getSharedComponent()->getNumberFormat();
  121. }
  122. /**
  123. * Build style array from subcomponents
  124. *
  125. * @param array $array
  126. * @return array
  127. */
  128. public function getStyleArray($array)
  129. {
  130. return array('numberformat' => $array);
  131. }
  132. /**
  133. * Apply styles from array
  134. *
  135. * <code>
  136. * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
  137. * array(
  138. * 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
  139. * )
  140. * );
  141. * </code>
  142. *
  143. * @param array $pStyles Array containing style information
  144. * @throws PHPExcel_Exception
  145. * @return PHPExcel_Style_NumberFormat
  146. */
  147. public function applyFromArray($pStyles = null)
  148. {
  149. if (is_array($pStyles)) {
  150. if ($this->_isSupervisor) {
  151. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
  152. } else {
  153. if (array_key_exists('code', $pStyles)) {
  154. $this->setFormatCode($pStyles['code']);
  155. }
  156. }
  157. } else {
  158. throw new PHPExcel_Exception("Invalid style array passed.");
  159. }
  160. return $this;
  161. }
  162. /**
  163. * Get Format Code
  164. *
  165. * @return string
  166. */
  167. public function getFormatCode()
  168. {
  169. if ($this->_isSupervisor) {
  170. return $this->getSharedComponent()->getFormatCode();
  171. }
  172. if ($this->_builtInFormatCode !== false)
  173. {
  174. return self::builtInFormatCode($this->_builtInFormatCode);
  175. }
  176. return $this->_formatCode;
  177. }
  178. /**
  179. * Set Format Code
  180. *
  181. * @param string $pValue
  182. * @return PHPExcel_Style_NumberFormat
  183. */
  184. public function setFormatCode($pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL)
  185. {
  186. /* echo $pValue;
  187. var_dump($this->_isSupervisor);
  188. die;*/
  189. if ($pValue == '') {
  190. $pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  191. }
  192. if ($this->_isSupervisor) {
  193. $styleArray = $this->getStyleArray(array('code' => $pValue));
  194. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  195. } else {
  196. $this->_formatCode = $pValue;
  197. $this->_builtInFormatCode = self::builtInFormatCodeIndex($pValue);
  198. }
  199. return $this;
  200. }
  201. /**
  202. * Get Built-In Format Code
  203. *
  204. * @return int
  205. */
  206. public function getBuiltInFormatCode()
  207. {
  208. if ($this->_isSupervisor) {
  209. return $this->getSharedComponent()->getBuiltInFormatCode();
  210. }
  211. return $this->_builtInFormatCode;
  212. }
  213. /**
  214. * Set Built-In Format Code
  215. *
  216. * @param int $pValue
  217. * @return PHPExcel_Style_NumberFormat
  218. */
  219. public function setBuiltInFormatCode($pValue = 0)
  220. {
  221. if ($this->_isSupervisor) {
  222. $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue)));
  223. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  224. } else {
  225. $this->_builtInFormatCode = $pValue;
  226. $this->_formatCode = self::builtInFormatCode($pValue);
  227. }
  228. return $this;
  229. }
  230. /**
  231. * Fill built-in format codes
  232. */
  233. private static function fillBuiltInFormatCodes()
  234. {
  235. // Built-in format codes
  236. if (is_null(self::$_builtInFormats)) {
  237. self::$_builtInFormats = array();
  238. // General
  239. self::$_builtInFormats[0] = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  240. self::$_builtInFormats[1] = '0';
  241. self::$_builtInFormats[2] = '0.00';
  242. self::$_builtInFormats[3] = '#,##0';
  243. self::$_builtInFormats[4] = '#,##0.00';
  244. self::$_builtInFormats[9] = '0%';
  245. self::$_builtInFormats[10] = '0.00%';
  246. self::$_builtInFormats[11] = '0.00E+00';
  247. self::$_builtInFormats[12] = '# ?/?';
  248. self::$_builtInFormats[13] = '# ??/??';
  249. self::$_builtInFormats[14] = 'mm-dd-yy';
  250. self::$_builtInFormats[15] = 'd-mmm-yy';
  251. self::$_builtInFormats[16] = 'd-mmm';
  252. self::$_builtInFormats[17] = 'mmm-yy';
  253. self::$_builtInFormats[18] = 'h:mm AM/PM';
  254. self::$_builtInFormats[19] = 'h:mm:ss AM/PM';
  255. self::$_builtInFormats[20] = 'h:mm';
  256. self::$_builtInFormats[21] = 'h:mm:ss';
  257. self::$_builtInFormats[22] = 'm/d/yy h:mm';
  258. self::$_builtInFormats[37] = '#,##0 ;(#,##0)';
  259. self::$_builtInFormats[38] = '#,##0 ;[Red](#,##0)';
  260. self::$_builtInFormats[39] = '#,##0.00;(#,##0.00)';
  261. self::$_builtInFormats[40] = '#,##0.00;[Red](#,##0.00)';
  262. self::$_builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
  263. self::$_builtInFormats[45] = 'mm:ss';
  264. self::$_builtInFormats[46] = '[h]:mm:ss';
  265. self::$_builtInFormats[47] = 'mmss.0';
  266. self::$_builtInFormats[48] = '##0.0E+0';
  267. self::$_builtInFormats[49] = '@';
  268. // CHT
  269. self::$_builtInFormats[27] = '[$-404]e/m/d';
  270. self::$_builtInFormats[30] = 'm/d/yy';
  271. self::$_builtInFormats[36] = '[$-404]e/m/d';
  272. self::$_builtInFormats[50] = '[$-404]e/m/d';
  273. self::$_builtInFormats[57] = '[$-404]e/m/d';
  274. // THA
  275. self::$_builtInFormats[59] = 't0';
  276. self::$_builtInFormats[60] = 't0.00';
  277. self::$_builtInFormats[61] = 't#,##0';
  278. self::$_builtInFormats[62] = 't#,##0.00';
  279. self::$_builtInFormats[67] = 't0%';
  280. self::$_builtInFormats[68] = 't0.00%';
  281. self::$_builtInFormats[69] = 't# ?/?';
  282. self::$_builtInFormats[70] = 't# ??/??';
  283. // Flip array (for faster lookups)
  284. self::$_flippedBuiltInFormats = array_flip(self::$_builtInFormats);
  285. }
  286. }
  287. /**
  288. * Get built-in format code
  289. *
  290. * @param int $pIndex
  291. * @return string
  292. */
  293. public static function builtInFormatCode($pIndex)
  294. {
  295. // Clean parameter
  296. $pIndex = intval($pIndex);
  297. // Ensure built-in format codes are available
  298. self::fillBuiltInFormatCodes();
  299. // Lookup format code
  300. if (isset(self::$_builtInFormats[$pIndex])) {
  301. return self::$_builtInFormats[$pIndex];
  302. }
  303. return '';
  304. }
  305. /**
  306. * Get built-in format code index
  307. *
  308. * @param string $formatCode
  309. * @return int|boolean
  310. */
  311. public static function builtInFormatCodeIndex($formatCode)
  312. {
  313. // Ensure built-in format codes are available
  314. self::fillBuiltInFormatCodes();
  315. // Lookup format code
  316. if (isset(self::$_flippedBuiltInFormats[$formatCode])) {
  317. return self::$_flippedBuiltInFormats[$formatCode];
  318. }
  319. return false;
  320. }
  321. /**
  322. * Get hash code
  323. *
  324. * @return string Hash code
  325. */
  326. public function getHashCode()
  327. {
  328. if ($this->_isSupervisor) {
  329. return $this->getSharedComponent()->getHashCode();
  330. }
  331. return md5(
  332. $this->_formatCode
  333. . $this->_builtInFormatCode
  334. . __CLASS__
  335. );
  336. }
  337. /**
  338. * Search/replace values to convert Excel date/time format masks to PHP format masks
  339. *
  340. * @var array
  341. */
  342. private static $_dateFormatReplacements = array(
  343. // first remove escapes related to non-format characters
  344. '\\' => '',
  345. // 12-hour suffix
  346. 'am/pm' => 'A',
  347. // 4-digit year
  348. 'e' => 'Y',
  349. 'yyyy' => 'Y',
  350. // 2-digit year
  351. 'yy' => 'y',
  352. // first letter of month - no php equivalent
  353. 'mmmmm' => 'M',
  354. // full month name
  355. 'mmmm' => 'F',
  356. // short month name
  357. 'mmm' => 'M',
  358. // mm is minutes if time, but can also be month w/leading zero
  359. // so we try to identify times be the inclusion of a : separator in the mask
  360. // It isn't perfect, but the best way I know how
  361. ':mm' => ':i',
  362. 'mm:' => 'i:',
  363. // month leading zero
  364. 'mm' => 'm',
  365. // month no leading zero
  366. 'm' => 'n',
  367. // full day of week name
  368. 'dddd' => 'l',
  369. // short day of week name
  370. 'ddd' => 'D',
  371. // days leading zero
  372. 'dd' => 'd',
  373. // days no leading zero
  374. 'd' => 'j',
  375. // seconds
  376. 'ss' => 's',
  377. // fractional seconds - no php equivalent
  378. '.s' => ''
  379. );
  380. /**
  381. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock)
  382. *
  383. * @var array
  384. */
  385. private static $_dateFormatReplacements24 = array(
  386. 'hh' => 'H',
  387. 'h' => 'G'
  388. );
  389. /**
  390. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock)
  391. *
  392. * @var array
  393. */
  394. private static $_dateFormatReplacements12 = array(
  395. 'hh' => 'h',
  396. 'h' => 'g'
  397. );
  398. private static function _formatAsDate(&$value, &$format)
  399. {
  400. // dvc: convert Excel formats to PHP date formats
  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. $format = preg_replace('/^(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format);
  405. // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case
  406. $format = strtolower($format);
  407. $format = strtr($format,self::$_dateFormatReplacements);
  408. if (!strpos($format,'A')) { // 24-hour time format
  409. $format = strtr($format,self::$_dateFormatReplacements24);
  410. } else { // 12-hour time format
  411. $format = strtr($format,self::$_dateFormatReplacements12);
  412. }
  413. $dateObj = PHPExcel_Shared_Date::ExcelToPHPObject($value);
  414. $value = $dateObj->format($format);
  415. }
  416. private static function _formatAsPercentage(&$value, &$format)
  417. {
  418. if ($format === self::FORMAT_PERCENTAGE) {
  419. $value = round( (100 * $value), 0) . '%';
  420. } else {
  421. if (preg_match('/\.[#0]+/i', $format, $m)) {
  422. $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1);
  423. $format = str_replace($m[0], $s, $format);
  424. }
  425. if (preg_match('/^[#0]+/', $format, $m)) {
  426. $format = str_replace($m[0], strlen($m[0]), $format);
  427. }
  428. $format = '%' . str_replace('%', 'f%%', $format);
  429. $value = sprintf($format, 100 * $value);
  430. }
  431. }
  432. private static function _formatAsFraction(&$value, &$format)
  433. {
  434. $sign = ($value < 0) ? '-' : '';
  435. $integerPart = floor(abs($value));
  436. $decimalPart = trim(fmod(abs($value),1),'0.');
  437. $decimalLength = strlen($decimalPart);
  438. $decimalDivisor = pow(10,$decimalLength);
  439. $GCD = PHPExcel_Calculation_MathTrig::GCD($decimalPart,$decimalDivisor);
  440. $adjustedDecimalPart = $decimalPart/$GCD;
  441. $adjustedDecimalDivisor = $decimalDivisor/$GCD;
  442. if ((strpos($format,'0') !== false) || (strpos($format,'#') !== false) || (substr($format,0,3) == '? ?')) {
  443. if ($integerPart == 0) {
  444. $integerPart = '';
  445. }
  446. $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
  447. } else {
  448. $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
  449. $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
  450. }
  451. }
  452. private static function _complexNumberFormatMask($number, $mask) {
  453. if (strpos($mask,'.') !== false) {
  454. $numbers = explode('.', $number . '.0');
  455. $masks = explode('.', $mask . '.0');
  456. $result1 = self::_complexNumberFormatMask($numbers[0], $masks[0]);
  457. $result2 = strrev(self::_complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1])));
  458. return $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 $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. // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
  553. $format = str_replace(array('"','*'), '', $format);
  554. // Find out if we need thousands separator
  555. // This is indicated by a comma enclosed by a digit placeholder:
  556. // #,# or 0,0
  557. $useThousands = preg_match('/(#,#|0,0)/', $format);
  558. if ($useThousands) {
  559. $format = preg_replace('/0,0/', '00', $format);
  560. $format = preg_replace('/#,#/', '##', $format);
  561. }
  562. // Scale thousands, millions,...
  563. // This is indicated by a number of commas after a digit placeholder:
  564. // #, or 0.0,,
  565. $scale = 1; // same as no scale
  566. $matches = array();
  567. if (preg_match('/(#|0)(,+)/', $format, $matches)) {
  568. $scale = pow(1000, strlen($matches[2]));
  569. // strip the commas
  570. $format = preg_replace('/0,+/', '0', $format);
  571. $format = preg_replace('/#,+/', '#', $format);
  572. }
  573. if (preg_match('/#?.*\?\/\?/', $format, $m)) {
  574. //echo 'Format mask is fractional '.$format.' <br />';
  575. if ($value != (int)$value) {
  576. self::_formatAsFraction($value, $format);
  577. }
  578. } else {
  579. // Handle the number itself
  580. // scale number
  581. $value = $value / $scale;
  582. // Strip #
  583. $format = preg_replace('/\\#/', '0', $format);
  584. $n = "/\[[^\]]+\]/";
  585. $m = preg_replace($n, '', $format);
  586. $number_regex = "/(0+)(\.?)(0*)/";
  587. if (preg_match($number_regex, $m, $matches)) {
  588. $left = $matches[1];
  589. $dec = $matches[2];
  590. $right = $matches[3];
  591. // minimun width of formatted number (including dot)
  592. $minWidth = strlen($left) + strlen($dec) + strlen($right);
  593. if ($useThousands) {
  594. $value = number_format(
  595. $value
  596. , strlen($right)
  597. , PHPExcel_Shared_String::getDecimalSeparator()
  598. , PHPExcel_Shared_String::getThousandsSeparator()
  599. );
  600. $value = preg_replace($number_regex, $value, $format);
  601. } else {
  602. if (preg_match('/[0#]E[+-]0/i', $format)) {
  603. // Scientific format
  604. $value = sprintf('%5.2E', $value);
  605. } elseif (preg_match('/0([^\d\.]+)0/', $format)) {
  606. $value = self::_complexNumberFormatMask($value, $format);
  607. } else {
  608. $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
  609. $value = sprintf($sprintf_pattern, $value);
  610. $value = preg_replace($number_regex, $value, $format);
  611. }
  612. }
  613. }
  614. }
  615. if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
  616. // Currency or Accounting
  617. $currencyFormat = $m[0];
  618. $currencyCode = $m[1];
  619. list($currencyCode) = explode('-',$currencyCode);
  620. if ($currencyCode == '') {
  621. $currencyCode = PHPExcel_Shared_String::getCurrencyCode();
  622. }
  623. $value = preg_replace('/\[\$([^\]]*)\]/u',$currencyCode,$value);
  624. }
  625. }
  626. }
  627. // Additional formatting provided by callback function
  628. if ($callBack !== null) {
  629. list($writerInstance, $function) = $callBack;
  630. $value = $writerInstance->$function($value, $formatColor);
  631. }
  632. return $value;
  633. }
  634. }