Excel2003XML.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. if (!defined('PHPEXCEL_ROOT')) {
  8. /**
  9. * @ignore
  10. */
  11. define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
  12. require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
  13. }
  14. /**
  15. * PHPExcel_Reader_Excel2003XML
  16. *
  17. * Copyright (c) 2006 - 2015 PHPExcel
  18. *
  19. * This library is free software; you can redistribute it and/or
  20. * modify it under the terms of the GNU Lesser General Public
  21. * License as published by the Free Software Foundation; either
  22. * version 2.1 of the License, or (at your option) any later version.
  23. *
  24. * This library is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  27. * Lesser General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Lesser General Public
  30. * License along with this library; if not, write to the Free Software
  31. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  32. *
  33. * @category PHPExcel
  34. * @package PHPExcel_Reader
  35. * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
  36. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  37. * @version ##VERSION##, ##DATE##
  38. */
  39. class PHPExcel_Reader_Excel2003XML extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
  40. {
  41. /**
  42. * Formats
  43. *
  44. * @var array
  45. */
  46. protected $styles = array();
  47. /**
  48. * Character set used in the file
  49. *
  50. * @var string
  51. */
  52. protected $charSet = 'UTF-8';
  53. /**
  54. * Create a new PHPExcel_Reader_Excel2003XML
  55. */
  56. public function __construct()
  57. {
  58. $this->readFilter = new PHPExcel_Reader_DefaultReadFilter();
  59. }
  60. /**
  61. * Can the current PHPExcel_Reader_IReader read the file?
  62. *
  63. * @param string $pFilename
  64. * @return boolean
  65. * @throws PHPExcel_Reader_Exception
  66. */
  67. public function canRead($pFilename)
  68. {
  69. // Office xmlns:o="urn:schemas-microsoft-com:office:office"
  70. // Excel xmlns:x="urn:schemas-microsoft-com:office:excel"
  71. // XML Spreadsheet xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  72. // Spreadsheet component xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet"
  73. // XML schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
  74. // XML data type xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
  75. // MS-persist recordset xmlns:rs="urn:schemas-microsoft-com:rowset"
  76. // Rowset xmlns:z="#RowsetSchema"
  77. //
  78. $signature = array(
  79. '<?xml version="1.0"',
  80. '<?mso-application progid="Excel.Sheet"?>'
  81. );
  82. // Open file
  83. $this->openFile($pFilename);
  84. $fileHandle = $this->fileHandle;
  85. // Read sample data (first 2 KB will do)
  86. $data = fread($fileHandle, 2048);
  87. fclose($fileHandle);
  88. $valid = true;
  89. foreach ($signature as $match) {
  90. // every part of the signature must be present
  91. if (strpos($data, $match) === false) {
  92. $valid = false;
  93. break;
  94. }
  95. }
  96. // Retrieve charset encoding
  97. if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/um', $data, $matches)) {
  98. $this->charSet = strtoupper($matches[1]);
  99. }
  100. // echo 'Character Set is ', $this->charSet,'<br />';
  101. return $valid;
  102. }
  103. /**
  104. * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object
  105. *
  106. * @param string $pFilename
  107. * @throws PHPExcel_Reader_Exception
  108. */
  109. public function listWorksheetNames($pFilename)
  110. {
  111. // Check if file exists
  112. if (!file_exists($pFilename)) {
  113. throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  114. }
  115. if (!$this->canRead($pFilename)) {
  116. throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
  117. }
  118. $worksheetNames = array();
  119. $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
  120. $namespaces = $xml->getNamespaces(true);
  121. $xml_ss = $xml->children($namespaces['ss']);
  122. foreach ($xml_ss->Worksheet as $worksheet) {
  123. $worksheet_ss = $worksheet->attributes($namespaces['ss']);
  124. $worksheetNames[] = self::convertStringEncoding((string) $worksheet_ss['Name'], $this->charSet);
  125. }
  126. return $worksheetNames;
  127. }
  128. /**
  129. * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
  130. *
  131. * @param string $pFilename
  132. * @throws PHPExcel_Reader_Exception
  133. */
  134. public function listWorksheetInfo($pFilename)
  135. {
  136. // Check if file exists
  137. if (!file_exists($pFilename)) {
  138. throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  139. }
  140. $worksheetInfo = array();
  141. $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
  142. $namespaces = $xml->getNamespaces(true);
  143. $worksheetID = 1;
  144. $xml_ss = $xml->children($namespaces['ss']);
  145. foreach ($xml_ss->Worksheet as $worksheet) {
  146. $worksheet_ss = $worksheet->attributes($namespaces['ss']);
  147. $tmpInfo = array();
  148. $tmpInfo['worksheetName'] = '';
  149. $tmpInfo['lastColumnLetter'] = 'A';
  150. $tmpInfo['lastColumnIndex'] = 0;
  151. $tmpInfo['totalRows'] = 0;
  152. $tmpInfo['totalColumns'] = 0;
  153. if (isset($worksheet_ss['Name'])) {
  154. $tmpInfo['worksheetName'] = (string) $worksheet_ss['Name'];
  155. } else {
  156. $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}";
  157. }
  158. if (isset($worksheet->Table->Row)) {
  159. $rowIndex = 0;
  160. foreach ($worksheet->Table->Row as $rowData) {
  161. $columnIndex = 0;
  162. $rowHasData = false;
  163. foreach ($rowData->Cell as $cell) {
  164. if (isset($cell->Data)) {
  165. $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
  166. $rowHasData = true;
  167. }
  168. ++$columnIndex;
  169. }
  170. ++$rowIndex;
  171. if ($rowHasData) {
  172. $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
  173. }
  174. }
  175. }
  176. $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
  177. $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;
  178. $worksheetInfo[] = $tmpInfo;
  179. ++$worksheetID;
  180. }
  181. return $worksheetInfo;
  182. }
  183. /**
  184. * Loads PHPExcel from file
  185. *
  186. * @param string $pFilename
  187. * @return PHPExcel
  188. * @throws PHPExcel_Reader_Exception
  189. */
  190. public function load($pFilename)
  191. {
  192. // Create new PHPExcel
  193. $objPHPExcel = new PHPExcel();
  194. $objPHPExcel->removeSheetByIndex(0);
  195. // Load into this instance
  196. return $this->loadIntoExisting($pFilename, $objPHPExcel);
  197. }
  198. protected static function identifyFixedStyleValue($styleList, &$styleAttributeValue)
  199. {
  200. $styleAttributeValue = strtolower($styleAttributeValue);
  201. foreach ($styleList as $style) {
  202. if ($styleAttributeValue == strtolower($style)) {
  203. $styleAttributeValue = $style;
  204. return true;
  205. }
  206. }
  207. return false;
  208. }
  209. /**
  210. * pixel units to excel width units(units of 1/256th of a character width)
  211. * @param pxs
  212. * @return
  213. */
  214. protected static function pixel2WidthUnits($pxs)
  215. {
  216. $UNIT_OFFSET_MAP = array(0, 36, 73, 109, 146, 182, 219);
  217. $widthUnits = 256 * ($pxs / 7);
  218. $widthUnits += $UNIT_OFFSET_MAP[($pxs % 7)];
  219. return $widthUnits;
  220. }
  221. /**
  222. * excel width units(units of 1/256th of a character width) to pixel units
  223. * @param widthUnits
  224. * @return
  225. */
  226. protected static function widthUnits2Pixel($widthUnits)
  227. {
  228. $pixels = ($widthUnits / 256) * 7;
  229. $offsetWidthUnits = $widthUnits % 256;
  230. $pixels += round($offsetWidthUnits / (256 / 7));
  231. return $pixels;
  232. }
  233. protected static function hex2str($hex)
  234. {
  235. return chr(hexdec($hex[1]));
  236. }
  237. /**
  238. * Loads PHPExcel from file into PHPExcel instance
  239. *
  240. * @param string $pFilename
  241. * @param PHPExcel $objPHPExcel
  242. * @return PHPExcel
  243. * @throws PHPExcel_Reader_Exception
  244. */
  245. public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
  246. {
  247. $fromFormats = array('\-', '\ ');
  248. $toFormats = array('-', ' ');
  249. $underlineStyles = array (
  250. PHPExcel_Style_Font::UNDERLINE_NONE,
  251. PHPExcel_Style_Font::UNDERLINE_DOUBLE,
  252. PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING,
  253. PHPExcel_Style_Font::UNDERLINE_SINGLE,
  254. PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING
  255. );
  256. $verticalAlignmentStyles = array (
  257. PHPExcel_Style_Alignment::VERTICAL_BOTTOM,
  258. PHPExcel_Style_Alignment::VERTICAL_TOP,
  259. PHPExcel_Style_Alignment::VERTICAL_CENTER,
  260. PHPExcel_Style_Alignment::VERTICAL_JUSTIFY
  261. );
  262. $horizontalAlignmentStyles = array (
  263. PHPExcel_Style_Alignment::HORIZONTAL_GENERAL,
  264. PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
  265. PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
  266. PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
  267. PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS,
  268. PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY
  269. );
  270. $timezoneObj = new DateTimeZone('Europe/London');
  271. $GMT = new DateTimeZone('UTC');
  272. // Check if file exists
  273. if (!file_exists($pFilename)) {
  274. throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  275. }
  276. if (!$this->canRead($pFilename)) {
  277. throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
  278. }
  279. $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
  280. $namespaces = $xml->getNamespaces(true);
  281. $docProps = $objPHPExcel->getProperties();
  282. if (isset($xml->DocumentProperties[0])) {
  283. foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) {
  284. switch ($propertyName) {
  285. case 'Title':
  286. $docProps->setTitle(self::convertStringEncoding($propertyValue, $this->charSet));
  287. break;
  288. case 'Subject':
  289. $docProps->setSubject(self::convertStringEncoding($propertyValue, $this->charSet));
  290. break;
  291. case 'Author':
  292. $docProps->setCreator(self::convertStringEncoding($propertyValue, $this->charSet));
  293. break;
  294. case 'Created':
  295. $creationDate = strtotime($propertyValue);
  296. $docProps->setCreated($creationDate);
  297. break;
  298. case 'LastAuthor':
  299. $docProps->setLastModifiedBy(self::convertStringEncoding($propertyValue, $this->charSet));
  300. break;
  301. case 'LastSaved':
  302. $lastSaveDate = strtotime($propertyValue);
  303. $docProps->setModified($lastSaveDate);
  304. break;
  305. case 'Company':
  306. $docProps->setCompany(self::convertStringEncoding($propertyValue, $this->charSet));
  307. break;
  308. case 'Category':
  309. $docProps->setCategory(self::convertStringEncoding($propertyValue, $this->charSet));
  310. break;
  311. case 'Manager':
  312. $docProps->setManager(self::convertStringEncoding($propertyValue, $this->charSet));
  313. break;
  314. case 'Keywords':
  315. $docProps->setKeywords(self::convertStringEncoding($propertyValue, $this->charSet));
  316. break;
  317. case 'Description':
  318. $docProps->setDescription(self::convertStringEncoding($propertyValue, $this->charSet));
  319. break;
  320. }
  321. }
  322. }
  323. if (isset($xml->CustomDocumentProperties)) {
  324. foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) {
  325. $propertyAttributes = $propertyValue->attributes($namespaces['dt']);
  326. $propertyName = preg_replace_callback('/_x([0-9a-z]{4})_/', 'PHPExcel_Reader_Excel2003XML::hex2str', $propertyName);
  327. $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_UNKNOWN;
  328. switch ((string) $propertyAttributes) {
  329. case 'string':
  330. $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
  331. $propertyValue = trim($propertyValue);
  332. break;
  333. case 'boolean':
  334. $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN;
  335. $propertyValue = (bool) $propertyValue;
  336. break;
  337. case 'integer':
  338. $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_INTEGER;
  339. $propertyValue = intval($propertyValue);
  340. break;
  341. case 'float':
  342. $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT;
  343. $propertyValue = floatval($propertyValue);
  344. break;
  345. case 'dateTime.tz':
  346. $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE;
  347. $propertyValue = strtotime(trim($propertyValue));
  348. break;
  349. }
  350. $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType);
  351. }
  352. }
  353. foreach ($xml->Styles[0] as $style) {
  354. $style_ss = $style->attributes($namespaces['ss']);
  355. $styleID = (string) $style_ss['ID'];
  356. // echo 'Style ID = '.$styleID.'<br />';
  357. $this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : array();
  358. foreach ($style as $styleType => $styleData) {
  359. $styleAttributes = $styleData->attributes($namespaces['ss']);
  360. // echo $styleType.'<br />';
  361. switch ($styleType) {
  362. case 'Alignment':
  363. foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
  364. // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
  365. $styleAttributeValue = (string) $styleAttributeValue;
  366. switch ($styleAttributeKey) {
  367. case 'Vertical':
  368. if (self::identifyFixedStyleValue($verticalAlignmentStyles, $styleAttributeValue)) {
  369. $this->styles[$styleID]['alignment']['vertical'] = $styleAttributeValue;
  370. }
  371. break;
  372. case 'Horizontal':
  373. if (self::identifyFixedStyleValue($horizontalAlignmentStyles, $styleAttributeValue)) {
  374. $this->styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue;
  375. }
  376. break;
  377. case 'WrapText':
  378. $this->styles[$styleID]['alignment']['wrap'] = true;
  379. break;
  380. }
  381. }
  382. break;
  383. case 'Borders':
  384. foreach ($styleData->Border as $borderStyle) {
  385. $borderAttributes = $borderStyle->attributes($namespaces['ss']);
  386. $thisBorder = array();
  387. foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) {
  388. // echo $borderStyleKey.' = '.$borderStyleValue.'<br />';
  389. switch ($borderStyleKey) {
  390. case 'LineStyle':
  391. $thisBorder['style'] = PHPExcel_Style_Border::BORDER_MEDIUM;
  392. // $thisBorder['style'] = $borderStyleValue;
  393. break;
  394. case 'Weight':
  395. // $thisBorder['style'] = $borderStyleValue;
  396. break;
  397. case 'Position':
  398. $borderPosition = strtolower($borderStyleValue);
  399. break;
  400. case 'Color':
  401. $borderColour = substr($borderStyleValue, 1);
  402. $thisBorder['color']['rgb'] = $borderColour;
  403. break;
  404. }
  405. }
  406. if (!empty($thisBorder)) {
  407. if (($borderPosition == 'left') || ($borderPosition == 'right') || ($borderPosition == 'top') || ($borderPosition == 'bottom')) {
  408. $this->styles[$styleID]['borders'][$borderPosition] = $thisBorder;
  409. }
  410. }
  411. }
  412. break;
  413. case 'Font':
  414. foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
  415. // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
  416. $styleAttributeValue = (string) $styleAttributeValue;
  417. switch ($styleAttributeKey) {
  418. case 'FontName':
  419. $this->styles[$styleID]['font']['name'] = $styleAttributeValue;
  420. break;
  421. case 'Size':
  422. $this->styles[$styleID]['font']['size'] = $styleAttributeValue;
  423. break;
  424. case 'Color':
  425. $this->styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue, 1);
  426. break;
  427. case 'Bold':
  428. $this->styles[$styleID]['font']['bold'] = true;
  429. break;
  430. case 'Italic':
  431. $this->styles[$styleID]['font']['italic'] = true;
  432. break;
  433. case 'Underline':
  434. if (self::identifyFixedStyleValue($underlineStyles, $styleAttributeValue)) {
  435. $this->styles[$styleID]['font']['underline'] = $styleAttributeValue;
  436. }
  437. break;
  438. }
  439. }
  440. break;
  441. case 'Interior':
  442. foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
  443. // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
  444. switch ($styleAttributeKey) {
  445. case 'Color':
  446. $this->styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue, 1);
  447. break;
  448. }
  449. }
  450. break;
  451. case 'NumberFormat':
  452. foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
  453. // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
  454. $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue);
  455. switch ($styleAttributeValue) {
  456. case 'Short Date':
  457. $styleAttributeValue = 'dd/mm/yyyy';
  458. break;
  459. }
  460. if ($styleAttributeValue > '') {
  461. $this->styles[$styleID]['numberformat']['code'] = $styleAttributeValue;
  462. }
  463. }
  464. break;
  465. case 'Protection':
  466. foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
  467. // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
  468. }
  469. break;
  470. }
  471. }
  472. // print_r($this->styles[$styleID]);
  473. // echo '<hr />';
  474. }
  475. // echo '<hr />';
  476. $worksheetID = 0;
  477. $xml_ss = $xml->children($namespaces['ss']);
  478. foreach ($xml_ss->Worksheet as $worksheet) {
  479. $worksheet_ss = $worksheet->attributes($namespaces['ss']);
  480. if ((isset($this->loadSheetsOnly)) && (isset($worksheet_ss['Name'])) &&
  481. (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly))) {
  482. continue;
  483. }
  484. // echo '<h3>Worksheet: ', $worksheet_ss['Name'],'<h3>';
  485. //
  486. // Create new Worksheet
  487. $objPHPExcel->createSheet();
  488. $objPHPExcel->setActiveSheetIndex($worksheetID);
  489. if (isset($worksheet_ss['Name'])) {
  490. $worksheetName = self::convertStringEncoding((string) $worksheet_ss['Name'], $this->charSet);
  491. // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in
  492. // formula cells... during the load, all formulae should be correct, and we're simply bringing
  493. // the worksheet name in line with the formula, not the reverse
  494. $objPHPExcel->getActiveSheet()->setTitle($worksheetName, false);
  495. }
  496. $columnID = 'A';
  497. if (isset($worksheet->Table->Column)) {
  498. foreach ($worksheet->Table->Column as $columnData) {
  499. $columnData_ss = $columnData->attributes($namespaces['ss']);
  500. if (isset($columnData_ss['Index'])) {
  501. $columnID = PHPExcel_Cell::stringFromColumnIndex($columnData_ss['Index']-1);
  502. }
  503. if (isset($columnData_ss['Width'])) {
  504. $columnWidth = $columnData_ss['Width'];
  505. // echo '<b>Setting column width for '.$columnID.' to '.$columnWidth.'</b><br />';
  506. $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setWidth($columnWidth / 5.4);
  507. }
  508. ++$columnID;
  509. }
  510. }
  511. $rowID = 1;
  512. if (isset($worksheet->Table->Row)) {
  513. $additionalMergedCells = 0;
  514. foreach ($worksheet->Table->Row as $rowData) {
  515. $rowHasData = false;
  516. $row_ss = $rowData->attributes($namespaces['ss']);
  517. if (isset($row_ss['Index'])) {
  518. $rowID = (integer) $row_ss['Index'];
  519. }
  520. // echo '<b>Row '.$rowID.'</b><br />';
  521. $columnID = 'A';
  522. foreach ($rowData->Cell as $cell) {
  523. $cell_ss = $cell->attributes($namespaces['ss']);
  524. if (isset($cell_ss['Index'])) {
  525. $columnID = PHPExcel_Cell::stringFromColumnIndex($cell_ss['Index']-1);
  526. }
  527. $cellRange = $columnID.$rowID;
  528. if ($this->getReadFilter() !== null) {
  529. if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
  530. continue;
  531. }
  532. }
  533. if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) {
  534. $columnTo = $columnID;
  535. if (isset($cell_ss['MergeAcross'])) {
  536. $additionalMergedCells += (int)$cell_ss['MergeAcross'];
  537. $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] -1);
  538. }
  539. $rowTo = $rowID;
  540. if (isset($cell_ss['MergeDown'])) {
  541. $rowTo = $rowTo + $cell_ss['MergeDown'];
  542. }
  543. $cellRange .= ':'.$columnTo.$rowTo;
  544. $objPHPExcel->getActiveSheet()->mergeCells($cellRange);
  545. }
  546. $cellIsSet = $hasCalculatedValue = false;
  547. $cellDataFormula = '';
  548. if (isset($cell_ss['Formula'])) {
  549. $cellDataFormula = $cell_ss['Formula'];
  550. // added this as a check for array formulas
  551. if (isset($cell_ss['ArrayRange'])) {
  552. $cellDataCSEFormula = $cell_ss['ArrayRange'];
  553. // echo "found an array formula at ".$columnID.$rowID."<br />";
  554. }
  555. $hasCalculatedValue = true;
  556. }
  557. if (isset($cell->Data)) {
  558. $cellValue = $cellData = $cell->Data;
  559. $type = PHPExcel_Cell_DataType::TYPE_NULL;
  560. $cellData_ss = $cellData->attributes($namespaces['ss']);
  561. if (isset($cellData_ss['Type'])) {
  562. $cellDataType = $cellData_ss['Type'];
  563. switch ($cellDataType) {
  564. /*
  565. const TYPE_STRING = 's';
  566. const TYPE_FORMULA = 'f';
  567. const TYPE_NUMERIC = 'n';
  568. const TYPE_BOOL = 'b';
  569. const TYPE_NULL = 'null';
  570. const TYPE_INLINE = 'inlineStr';
  571. const TYPE_ERROR = 'e';
  572. */
  573. case 'String':
  574. $cellValue = self::convertStringEncoding($cellValue, $this->charSet);
  575. $type = PHPExcel_Cell_DataType::TYPE_STRING;
  576. break;
  577. case 'Number':
  578. $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
  579. $cellValue = (float) $cellValue;
  580. if (floor($cellValue) == $cellValue) {
  581. $cellValue = (integer) $cellValue;
  582. }
  583. break;
  584. case 'Boolean':
  585. $type = PHPExcel_Cell_DataType::TYPE_BOOL;
  586. $cellValue = ($cellValue != 0);
  587. break;
  588. case 'DateTime':
  589. $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
  590. $cellValue = PHPExcel_Shared_Date::PHPToExcel(strtotime($cellValue));
  591. break;
  592. case 'Error':
  593. $type = PHPExcel_Cell_DataType::TYPE_ERROR;
  594. break;
  595. }
  596. }
  597. if ($hasCalculatedValue) {
  598. // echo 'FORMULA<br />';
  599. $type = PHPExcel_Cell_DataType::TYPE_FORMULA;
  600. $columnNumber = PHPExcel_Cell::columnIndexFromString($columnID);
  601. if (substr($cellDataFormula, 0, 3) == 'of:') {
  602. $cellDataFormula = substr($cellDataFormula, 3);
  603. // echo 'Before: ', $cellDataFormula,'<br />';
  604. $temp = explode('"', $cellDataFormula);
  605. $key = false;
  606. foreach ($temp as &$value) {
  607. // Only replace in alternate array entries (i.e. non-quoted blocks)
  608. if ($key = !$key) {
  609. $value = str_replace(array('[.', '.', ']'), '', $value);
  610. }
  611. }
  612. } else {
  613. // Convert R1C1 style references to A1 style references (but only when not quoted)
  614. // echo 'Before: ', $cellDataFormula,'<br />';
  615. $temp = explode('"', $cellDataFormula);
  616. $key = false;
  617. foreach ($temp as &$value) {
  618. // Only replace in alternate array entries (i.e. non-quoted blocks)
  619. if ($key = !$key) {
  620. preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
  621. // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
  622. // through the formula from left to right. Reversing means that we work right to left.through
  623. // the formula
  624. $cellReferences = array_reverse($cellReferences);
  625. // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
  626. // then modify the formula to use that new reference
  627. foreach ($cellReferences as $cellReference) {
  628. $rowReference = $cellReference[2][0];
  629. // Empty R reference is the current row
  630. if ($rowReference == '') {
  631. $rowReference = $rowID;
  632. }
  633. // Bracketed R references are relative to the current row
  634. if ($rowReference{0} == '[') {
  635. $rowReference = $rowID + trim($rowReference, '[]');
  636. }
  637. $columnReference = $cellReference[4][0];
  638. // Empty C reference is the current column
  639. if ($columnReference == '') {
  640. $columnReference = $columnNumber;
  641. }
  642. // Bracketed C references are relative to the current column
  643. if ($columnReference{0} == '[') {
  644. $columnReference = $columnNumber + trim($columnReference, '[]');
  645. }
  646. $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference;
  647. $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
  648. }
  649. }
  650. }
  651. }
  652. unset($value);
  653. // Then rebuild the formula string
  654. $cellDataFormula = implode('"', $temp);
  655. // echo 'After: ', $cellDataFormula,'<br />';
  656. }
  657. // echo 'Cell '.$columnID.$rowID.' is a '.$type.' with a value of '.(($hasCalculatedValue) ? $cellDataFormula : $cellValue).'<br />';
  658. //
  659. $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type);
  660. if ($hasCalculatedValue) {
  661. // echo 'Formula result is '.$cellValue.'<br />';
  662. $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setCalculatedValue($cellValue);
  663. }
  664. $cellIsSet = $rowHasData = true;
  665. }
  666. if (isset($cell->Comment)) {
  667. // echo '<b>comment found</b><br />';
  668. $commentAttributes = $cell->Comment->attributes($namespaces['ss']);
  669. $author = 'unknown';
  670. if (isset($commentAttributes->Author)) {
  671. $author = (string)$commentAttributes->Author;
  672. // echo 'Author: ', $author,'<br />';
  673. }
  674. $node = $cell->Comment->Data->asXML();
  675. // $annotation = str_replace('html:','',substr($node,49,-10));
  676. // echo $annotation,'<br />';
  677. $annotation = strip_tags($node);
  678. // echo 'Annotation: ', $annotation,'<br />';
  679. $objPHPExcel->getActiveSheet()->getComment($columnID.$rowID)->setAuthor(self::convertStringEncoding($author, $this->charSet))->setText($this->parseRichText($annotation));
  680. }
  681. if (($cellIsSet) && (isset($cell_ss['StyleID']))) {
  682. $style = (string) $cell_ss['StyleID'];
  683. // echo 'Cell style for '.$columnID.$rowID.' is '.$style.'<br />';
  684. if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) {
  685. // echo 'Cell '.$columnID.$rowID.'<br />';
  686. // print_r($this->styles[$style]);
  687. // echo '<br />';
  688. if (!$objPHPExcel->getActiveSheet()->cellExists($columnID.$rowID)) {
  689. $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValue(null);
  690. }
  691. $objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]);
  692. }
  693. }
  694. ++$columnID;
  695. while ($additionalMergedCells > 0) {
  696. ++$columnID;
  697. $additionalMergedCells--;
  698. }
  699. }
  700. if ($rowHasData) {
  701. if (isset($row_ss['StyleID'])) {
  702. $rowStyle = $row_ss['StyleID'];
  703. }
  704. if (isset($row_ss['Height'])) {
  705. $rowHeight = $row_ss['Height'];
  706. // echo '<b>Setting row height to '.$rowHeight.'</b><br />';
  707. $objPHPExcel->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight);
  708. }
  709. }
  710. ++$rowID;
  711. }
  712. }
  713. ++$worksheetID;
  714. }
  715. // Return
  716. return $objPHPExcel;
  717. }
  718. protected static function convertStringEncoding($string, $charset)
  719. {
  720. if ($charset != 'UTF-8') {
  721. return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', $charset);
  722. }
  723. return $string;
  724. }
  725. protected function parseRichText($is = '')
  726. {
  727. $value = new PHPExcel_RichText();
  728. $value->createText(self::convertStringEncoding($is, $this->charSet));
  729. return $value;
  730. }
  731. }