PageRenderTime 29ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/Classes/PHPExcel/Writer/HTML.php

https://github.com/iGroup/PHPExcel
PHP | 1441 lines | 756 code | 204 blank | 481 comment | 161 complexity | d7967a3eb2f4f33817530ff161d5c931 MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2012 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_Writer_HTML
  23. * @copyright Copyright (c) 2006 - 2012 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_Writer_HTML
  29. *
  30. * @category PHPExcel
  31. * @package PHPExcel_Writer_HTML
  32. * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
  33. */
  34. class PHPExcel_Writer_HTML extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter {
  35. /**
  36. * PHPExcel object
  37. *
  38. * @var PHPExcel
  39. */
  40. protected $_phpExcel;
  41. /**
  42. * Sheet index to write
  43. *
  44. * @var int
  45. */
  46. private $_sheetIndex = 0;
  47. /**
  48. * Images root
  49. *
  50. * @var string
  51. */
  52. private $_imagesRoot = '.';
  53. /**
  54. * embed images, or link to images
  55. *
  56. * @var boolean
  57. */
  58. private $_embedImages = FALSE;
  59. /**
  60. * Use inline CSS?
  61. *
  62. * @var boolean
  63. */
  64. private $_useInlineCss = false;
  65. /**
  66. * Array of CSS styles
  67. *
  68. * @var array
  69. */
  70. private $_cssStyles = null;
  71. /**
  72. * Array of column widths in points
  73. *
  74. * @var array
  75. */
  76. private $_columnWidths = null;
  77. /**
  78. * Default font
  79. *
  80. * @var PHPExcel_Style_Font
  81. */
  82. private $_defaultFont;
  83. /**
  84. * Flag whether spans have been calculated
  85. *
  86. * @var boolean
  87. */
  88. private $_spansAreCalculated = false;
  89. /**
  90. * Excel cells that should not be written as HTML cells
  91. *
  92. * @var array
  93. */
  94. private $_isSpannedCell = array();
  95. /**
  96. * Excel cells that are upper-left corner in a cell merge
  97. *
  98. * @var array
  99. */
  100. private $_isBaseCell = array();
  101. /**
  102. * Excel rows that should not be written as HTML rows
  103. *
  104. * @var array
  105. */
  106. private $_isSpannedRow = array();
  107. /**
  108. * Is the current writer creating PDF?
  109. *
  110. * @var boolean
  111. */
  112. protected $_isPdf = false;
  113. /**
  114. * Generate the Navigation block
  115. *
  116. * @var boolean
  117. */
  118. private $_generateSheetNavigationBlock = true;
  119. /**
  120. * Create a new PHPExcel_Writer_HTML
  121. *
  122. * @param PHPExcel $phpExcel PHPExcel object
  123. */
  124. public function __construct(PHPExcel $phpExcel) {
  125. $this->_phpExcel = $phpExcel;
  126. $this->_defaultFont = $this->_phpExcel->getDefaultStyle()->getFont();
  127. }
  128. /**
  129. * Save PHPExcel to file
  130. *
  131. * @param string $pFilename
  132. * @throws PHPExcel_Writer_Exception
  133. */
  134. public function save($pFilename = null) {
  135. // garbage collect
  136. $this->_phpExcel->garbageCollect();
  137. $saveDebugLog = PHPExcel_Calculation::getInstance()->writeDebugLog;
  138. PHPExcel_Calculation::getInstance()->writeDebugLog = false;
  139. $saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
  140. PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);
  141. // Build CSS
  142. $this->buildCSS(!$this->_useInlineCss);
  143. // Open file
  144. $fileHandle = fopen($pFilename, 'wb+');
  145. if ($fileHandle === false) {
  146. throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing.");
  147. }
  148. // Write headers
  149. fwrite($fileHandle, $this->generateHTMLHeader(!$this->_useInlineCss));
  150. // Write navigation (tabs)
  151. if ((!$this->_isPdf) && ($this->_generateSheetNavigationBlock)) {
  152. fwrite($fileHandle, $this->generateNavigation());
  153. }
  154. // Write data
  155. fwrite($fileHandle, $this->generateSheetData());
  156. // Write footer
  157. fwrite($fileHandle, $this->generateHTMLFooter());
  158. // Close file
  159. fclose($fileHandle);
  160. PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
  161. PHPExcel_Calculation::getInstance()->writeDebugLog = $saveDebugLog;
  162. }
  163. /**
  164. * Map VAlign
  165. *
  166. * @param string $vAlign Vertical alignment
  167. * @return string
  168. */
  169. private function _mapVAlign($vAlign) {
  170. switch ($vAlign) {
  171. case PHPExcel_Style_Alignment::VERTICAL_BOTTOM: return 'bottom';
  172. case PHPExcel_Style_Alignment::VERTICAL_TOP: return 'top';
  173. case PHPExcel_Style_Alignment::VERTICAL_CENTER:
  174. case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY: return 'middle';
  175. default: return 'baseline';
  176. }
  177. }
  178. /**
  179. * Map HAlign
  180. *
  181. * @param string $hAlign Horizontal alignment
  182. * @return string|false
  183. */
  184. private function _mapHAlign($hAlign) {
  185. switch ($hAlign) {
  186. case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL: return false;
  187. case PHPExcel_Style_Alignment::HORIZONTAL_LEFT: return 'left';
  188. case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT: return 'right';
  189. case PHPExcel_Style_Alignment::HORIZONTAL_CENTER:
  190. case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS: return 'center';
  191. case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY: return 'justify';
  192. default: return false;
  193. }
  194. }
  195. /**
  196. * Map border style
  197. *
  198. * @param int $borderStyle Sheet index
  199. * @return string
  200. */
  201. private function _mapBorderStyle($borderStyle) {
  202. switch ($borderStyle) {
  203. case PHPExcel_Style_Border::BORDER_NONE: return 'none';
  204. case PHPExcel_Style_Border::BORDER_DASHDOT: return '1px dashed';
  205. case PHPExcel_Style_Border::BORDER_DASHDOTDOT: return '1px dotted';
  206. case PHPExcel_Style_Border::BORDER_DASHED: return '1px dashed';
  207. case PHPExcel_Style_Border::BORDER_DOTTED: return '1px dotted';
  208. case PHPExcel_Style_Border::BORDER_DOUBLE: return '3px double';
  209. case PHPExcel_Style_Border::BORDER_HAIR: return '1px solid';
  210. case PHPExcel_Style_Border::BORDER_MEDIUM: return '2px solid';
  211. case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: return '2px dashed';
  212. case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: return '2px dotted';
  213. case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: return '2px dashed';
  214. case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: return '2px dashed';
  215. case PHPExcel_Style_Border::BORDER_THICK: return '3px solid';
  216. case PHPExcel_Style_Border::BORDER_THIN: return '1px solid';
  217. default: return '1px solid'; // map others to thin
  218. }
  219. }
  220. /**
  221. * Get sheet index
  222. *
  223. * @return int
  224. */
  225. public function getSheetIndex() {
  226. return $this->_sheetIndex;
  227. }
  228. /**
  229. * Set sheet index
  230. *
  231. * @param int $pValue Sheet index
  232. * @return PHPExcel_Writer_HTML
  233. */
  234. public function setSheetIndex($pValue = 0) {
  235. $this->_sheetIndex = $pValue;
  236. return $this;
  237. }
  238. /**
  239. * Get sheet index
  240. *
  241. * @return boolean
  242. */
  243. public function getGenerateSheetNavigationBlock() {
  244. return $this->_generateSheetNavigationBlock;
  245. }
  246. /**
  247. * Set sheet index
  248. *
  249. * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not
  250. * @return PHPExcel_Writer_HTML
  251. */
  252. public function setGenerateSheetNavigationBlock($pValue = true) {
  253. $this->_generateSheetNavigationBlock = (bool) $pValue;
  254. return $this;
  255. }
  256. /**
  257. * Write all sheets (resets sheetIndex to NULL)
  258. */
  259. public function writeAllSheets() {
  260. $this->_sheetIndex = null;
  261. return $this;
  262. }
  263. /**
  264. * Generate HTML header
  265. *
  266. * @param boolean $pIncludeStyles Include styles?
  267. * @return string
  268. * @throws PHPExcel_Writer_Exception
  269. */
  270. public function generateHTMLHeader($pIncludeStyles = false) {
  271. // PHPExcel object known?
  272. if (is_null($this->_phpExcel)) {
  273. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  274. }
  275. // Construct HTML
  276. $properties = $this->_phpExcel->getProperties();
  277. $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' . PHP_EOL;
  278. $html .= '<!-- Generated by PHPExcel - http://www.phpexcel.net -->' . PHP_EOL;
  279. $html .= '<html>' . PHP_EOL;
  280. $html .= ' <head>' . PHP_EOL;
  281. $html .= ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . PHP_EOL;
  282. if ($properties->getTitle() > '')
  283. $html .= ' <title>' . htmlspecialchars($properties->getTitle()) . '</title>' . PHP_EOL;
  284. if ($properties->getCreator() > '')
  285. $html .= ' <meta name="author" content="' . htmlspecialchars($properties->getCreator()) . '" />' . PHP_EOL;
  286. if ($properties->getTitle() > '')
  287. $html .= ' <meta name="title" content="' . htmlspecialchars($properties->getTitle()) . '" />' . PHP_EOL;
  288. if ($properties->getDescription() > '')
  289. $html .= ' <meta name="description" content="' . htmlspecialchars($properties->getDescription()) . '" />' . PHP_EOL;
  290. if ($properties->getSubject() > '')
  291. $html .= ' <meta name="subject" content="' . htmlspecialchars($properties->getSubject()) . '" />' . PHP_EOL;
  292. if ($properties->getKeywords() > '')
  293. $html .= ' <meta name="keywords" content="' . htmlspecialchars($properties->getKeywords()) . '" />' . PHP_EOL;
  294. if ($properties->getCategory() > '')
  295. $html .= ' <meta name="category" content="' . htmlspecialchars($properties->getCategory()) . '" />' . PHP_EOL;
  296. if ($properties->getCompany() > '')
  297. $html .= ' <meta name="company" content="' . htmlspecialchars($properties->getCompany()) . '" />' . PHP_EOL;
  298. if ($properties->getManager() > '')
  299. $html .= ' <meta name="manager" content="' . htmlspecialchars($properties->getManager()) . '" />' . PHP_EOL;
  300. if ($pIncludeStyles) {
  301. $html .= $this->generateStyles(true);
  302. }
  303. $html .= ' </head>' . PHP_EOL;
  304. $html .= '' . PHP_EOL;
  305. $html .= ' <body>' . PHP_EOL;
  306. // Return
  307. return $html;
  308. }
  309. /**
  310. * Generate sheet data
  311. *
  312. * @return string
  313. * @throws PHPExcel_Writer_Exception
  314. */
  315. public function generateSheetData() {
  316. // PHPExcel object known?
  317. if (is_null($this->_phpExcel)) {
  318. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  319. }
  320. // Ensure that Spans have been calculated?
  321. if (!$this->_spansAreCalculated) {
  322. $this->_calculateSpans();
  323. }
  324. // Fetch sheets
  325. $sheets = array();
  326. if (is_null($this->_sheetIndex)) {
  327. $sheets = $this->_phpExcel->getAllSheets();
  328. } else {
  329. $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
  330. }
  331. // Construct HTML
  332. $html = '';
  333. // Loop all sheets
  334. $sheetId = 0;
  335. foreach ($sheets as $sheet) {
  336. // Write table header
  337. $html .= $this->_generateTableHeader($sheet);
  338. // Get worksheet dimension
  339. $dimension = explode(':', $sheet->calculateWorksheetDimension());
  340. $dimension[0] = PHPExcel_Cell::coordinateFromString($dimension[0]);
  341. $dimension[0][0] = PHPExcel_Cell::columnIndexFromString($dimension[0][0]) - 1;
  342. $dimension[1] = PHPExcel_Cell::coordinateFromString($dimension[1]);
  343. $dimension[1][0] = PHPExcel_Cell::columnIndexFromString($dimension[1][0]) - 1;
  344. // row min,max
  345. $rowMin = $dimension[0][1];
  346. $rowMax = $dimension[1][1];
  347. // calculate start of <tbody>, <thead>
  348. $tbodyStart = $rowMin;
  349. $tbodyEnd = $rowMax;
  350. $theadStart = $theadEnd = 0; // default: no <thead> no </thead>
  351. if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
  352. $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();
  353. // we can only support repeating rows that start at top row
  354. if ($rowsToRepeatAtTop[0] == 1) {
  355. $theadStart = $rowsToRepeatAtTop[0];
  356. $theadEnd = $rowsToRepeatAtTop[1];
  357. $tbodyStart = $rowsToRepeatAtTop[1] + 1;
  358. }
  359. }
  360. // Loop through cells
  361. $row = $rowMin-1;
  362. while($row++ < $rowMax) {
  363. // <thead> ?
  364. if ($row == $theadStart) {
  365. $html .= ' <thead>' . PHP_EOL;
  366. }
  367. // <tbody> ?
  368. if ($row == $tbodyStart) {
  369. $html .= ' <tbody>' . PHP_EOL;
  370. }
  371. // Write row if there are HTML table cells in it
  372. if ( !isset($this->_isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row]) ) {
  373. // Start a new rowData
  374. $rowData = array();
  375. // Loop through columns
  376. $column = $dimension[0][0] - 1;
  377. while($column++ < $dimension[1][0]) {
  378. // Cell exists?
  379. if ($sheet->cellExistsByColumnAndRow($column, $row)) {
  380. $rowData[$column] = $sheet->getCellByColumnAndRow($column, $row);
  381. } else {
  382. $rowData[$column] = '';
  383. }
  384. }
  385. $html .= $this->_generateRow($sheet, $rowData, $row - 1);
  386. }
  387. // </thead> ?
  388. if ($row == $theadEnd) {
  389. $html .= ' </thead>' . PHP_EOL;
  390. }
  391. // </tbody> ?
  392. if ($row == $tbodyEnd) {
  393. $html .= ' </tbody>' . PHP_EOL;
  394. }
  395. }
  396. // Write table footer
  397. $html .= $this->_generateTableFooter();
  398. // Writing PDF?
  399. if ($this->_isPdf) {
  400. if (is_null($this->_sheetIndex) && $sheetId + 1 < $this->_phpExcel->getSheetCount()) {
  401. $html .= '<div style="page-break-before:always" />';
  402. }
  403. }
  404. // Next sheet
  405. ++$sheetId;
  406. }
  407. // Return
  408. return $html;
  409. }
  410. /**
  411. * Generate sheet tabs
  412. *
  413. * @return string
  414. * @throws PHPExcel_Writer_Exception
  415. */
  416. public function generateNavigation()
  417. {
  418. // PHPExcel object known?
  419. if (is_null($this->_phpExcel)) {
  420. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  421. }
  422. // Fetch sheets
  423. $sheets = array();
  424. if (is_null($this->_sheetIndex)) {
  425. $sheets = $this->_phpExcel->getAllSheets();
  426. } else {
  427. $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
  428. }
  429. // Construct HTML
  430. $html = '';
  431. // Only if there are more than 1 sheets
  432. if (count($sheets) > 1) {
  433. // Loop all sheets
  434. $sheetId = 0;
  435. $html .= '<ul class="navigation">' . PHP_EOL;
  436. foreach ($sheets as $sheet) {
  437. $html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL;
  438. ++$sheetId;
  439. }
  440. $html .= '</ul>' . PHP_EOL;
  441. }
  442. return $html;
  443. }
  444. /**
  445. * Generate image tag in cell
  446. *
  447. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  448. * @param string $coordinates Cell coordinates
  449. * @return string
  450. * @throws PHPExcel_Writer_Exception
  451. */
  452. private function _writeImageInCell(PHPExcel_Worksheet $pSheet, $coordinates) {
  453. // Construct HTML
  454. $html = '';
  455. // Write images
  456. foreach ($pSheet->getDrawingCollection() as $drawing) {
  457. if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
  458. if ($drawing->getCoordinates() == $coordinates) {
  459. $filename = $drawing->getPath();
  460. // Strip off eventual '.'
  461. if (substr($filename, 0, 1) == '.') {
  462. $filename = substr($filename, 1);
  463. }
  464. // Prepend images root
  465. $filename = $this->getImagesRoot() . $filename;
  466. // Strip off eventual '.'
  467. if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
  468. $filename = substr($filename, 1);
  469. }
  470. // Convert UTF8 data to PCDATA
  471. $filename = htmlspecialchars($filename);
  472. $html .= PHP_EOL;
  473. if ((!$this->_embedImages) || ($this->_isPdf)) {
  474. $imageData = $filename;
  475. } else {
  476. $imageDetails = getimagesize($filename);
  477. if ($fp = fopen($filename,"rb", 0)) {
  478. $picture = fread($fp,filesize($filename));
  479. fclose($fp);
  480. // base64 encode the binary data, then break it
  481. // into chunks according to RFC 2045 semantics
  482. $base64 = chunk_split(base64_encode($picture));
  483. $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
  484. } else {
  485. $imageData = $filename;
  486. }
  487. }
  488. $html .= '<img style="position: relative; left: ' . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' . $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . $imageData . '" border="0" width="' . $drawing->getWidth() . '" height="' . $drawing->getHeight() . '" />' . PHP_EOL;
  489. }
  490. }
  491. }
  492. // Return
  493. return $html;
  494. }
  495. /**
  496. * Generate chart tag in cell
  497. *
  498. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  499. * @param string $coordinates Cell coordinates
  500. * @return string
  501. * @throws PHPExcel_Writer_Exception
  502. */
  503. private function _writeChartInCell(PHPExcel_Worksheet $pSheet, $coordinates) {
  504. // Construct HTML
  505. $html = '';
  506. // Write charts
  507. foreach ($pSheet->getChartCollection() as $chart) {
  508. if ($chart instanceof PHPExcel_Chart) {
  509. $chartCoordinates = $chart->getTopLeftPosition();
  510. if ($chartCoordinates['cell'] == $coordinates) {
  511. $chartFileName = tempnam(PHPExcel_Shared_File::sys_get_temp_dir());
  512. if (!$chart->render($chartFileName)) {
  513. return;
  514. }
  515. $html .= PHP_EOL;
  516. $imageDetails = getimagesize($chartFileName);
  517. if ($fp = fopen($chartFileName,"rb", 0)) {
  518. $picture = fread($fp,filesize($chartFileName));
  519. fclose($fp);
  520. // base64 encode the binary data, then break it
  521. // into chunks according to RFC 2045 semantics
  522. $base64 = chunk_split(base64_encode($picture));
  523. $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
  524. $html .= '<img style="position: relative; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $chart->getWidth() . 'px; height: ' . $chart->getHeight() . 'px;" src="' . $imageData . '" border="0" />' . PHP_EOL;
  525. unlink($chartFileName);
  526. }
  527. }
  528. }
  529. }
  530. // Return
  531. return $html;
  532. }
  533. /**
  534. * Generate CSS styles
  535. *
  536. * @param boolean $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>)
  537. * @return string
  538. * @throws PHPExcel_Writer_Exception
  539. */
  540. public function generateStyles($generateSurroundingHTML = true) {
  541. // PHPExcel object known?
  542. if (is_null($this->_phpExcel)) {
  543. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  544. }
  545. // Build CSS
  546. $css = $this->buildCSS($generateSurroundingHTML);
  547. // Construct HTML
  548. $html = '';
  549. // Start styles
  550. if ($generateSurroundingHTML) {
  551. $html .= ' <style type="text/css">' . PHP_EOL;
  552. $html .= ' html { ' . $this->_assembleCSS($css['html']) . ' }' . PHP_EOL;
  553. }
  554. // Write all other styles
  555. foreach ($css as $styleName => $styleDefinition) {
  556. if ($styleName != 'html') {
  557. $html .= ' ' . $styleName . ' { ' . $this->_assembleCSS($styleDefinition) . ' }' . PHP_EOL;
  558. }
  559. }
  560. // End styles
  561. if ($generateSurroundingHTML) {
  562. $html .= ' </style>' . PHP_EOL;
  563. }
  564. // Return
  565. return $html;
  566. }
  567. /**
  568. * Build CSS styles
  569. *
  570. * @param boolean $generateSurroundingHTML Generate surrounding HTML style? (html { })
  571. * @return array
  572. * @throws PHPExcel_Writer_Exception
  573. */
  574. public function buildCSS($generateSurroundingHTML = true) {
  575. // PHPExcel object known?
  576. if (is_null($this->_phpExcel)) {
  577. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  578. }
  579. // Cached?
  580. if (!is_null($this->_cssStyles)) {
  581. return $this->_cssStyles;
  582. }
  583. // Ensure that spans have been calculated
  584. if (!$this->_spansAreCalculated) {
  585. $this->_calculateSpans();
  586. }
  587. // Construct CSS
  588. $css = array();
  589. // Start styles
  590. if ($generateSurroundingHTML) {
  591. // html { }
  592. $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif';
  593. $css['html']['font-size'] = '11pt';
  594. $css['html']['background-color'] = 'white';
  595. }
  596. // table { }
  597. $css['table']['border-collapse'] = 'collapse';
  598. if (!$this->_isPdf) {
  599. $css['table']['page-break-after'] = 'always';
  600. }
  601. // .gridlines td { }
  602. $css['.gridlines td']['border'] = '1px dotted black';
  603. // .b {}
  604. $css['.b']['text-align'] = 'center'; // BOOL
  605. // .e {}
  606. $css['.e']['text-align'] = 'center'; // ERROR
  607. // .f {}
  608. $css['.f']['text-align'] = 'right'; // FORMULA
  609. // .inlineStr {}
  610. $css['.inlineStr']['text-align'] = 'left'; // INLINE
  611. // .n {}
  612. $css['.n']['text-align'] = 'right'; // NUMERIC
  613. // .s {}
  614. $css['.s']['text-align'] = 'left'; // STRING
  615. // Calculate cell style hashes
  616. foreach ($this->_phpExcel->getCellXfCollection() as $index => $style) {
  617. $css['td.style' . $index] = $this->_createCSSStyle( $style );
  618. }
  619. // Fetch sheets
  620. $sheets = array();
  621. if (is_null($this->_sheetIndex)) {
  622. $sheets = $this->_phpExcel->getAllSheets();
  623. } else {
  624. $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
  625. }
  626. // Build styles per sheet
  627. foreach ($sheets as $sheet) {
  628. // Calculate hash code
  629. $sheetIndex = $sheet->getParent()->getIndex($sheet);
  630. // Build styles
  631. // Calculate column widths
  632. $sheet->calculateColumnWidths();
  633. // col elements, initialize
  634. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) - 1;
  635. $column = -1;
  636. while($column++ < $highestColumnIndex) {
  637. $this->_columnWidths[$sheetIndex][$column] = 42; // approximation
  638. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt';
  639. }
  640. // col elements, loop through columnDimensions and set width
  641. foreach ($sheet->getColumnDimensions() as $columnDimension) {
  642. if (($width = PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth(), $this->_defaultFont)) >= 0) {
  643. $width = PHPExcel_Shared_Drawing::pixelsToPoints($width);
  644. $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1;
  645. $this->_columnWidths[$sheetIndex][$column] = $width;
  646. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt';
  647. if ($columnDimension->getVisible() === false) {
  648. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse';
  649. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['*display'] = 'none'; // target IE6+7
  650. }
  651. }
  652. }
  653. // Default row height
  654. $rowDimension = $sheet->getDefaultRowDimension();
  655. // table.sheetN tr { }
  656. $css['table.sheet' . $sheetIndex . ' tr'] = array();
  657. if ($rowDimension->getRowHeight() == -1) {
  658. $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont());
  659. } else {
  660. $pt_height = $rowDimension->getRowHeight();
  661. }
  662. $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt';
  663. if ($rowDimension->getVisible() === false) {
  664. $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none';
  665. $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden';
  666. }
  667. // Calculate row heights
  668. foreach ($sheet->getRowDimensions() as $rowDimension) {
  669. $row = $rowDimension->getRowIndex() - 1;
  670. // table.sheetN tr.rowYYYYYY { }
  671. $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = array();
  672. if ($rowDimension->getRowHeight() == -1) {
  673. $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont());
  674. } else {
  675. $pt_height = $rowDimension->getRowHeight();
  676. }
  677. $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt';
  678. if ($rowDimension->getVisible() === false) {
  679. $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none';
  680. $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden';
  681. }
  682. }
  683. }
  684. // Cache
  685. if (is_null($this->_cssStyles)) {
  686. $this->_cssStyles = $css;
  687. }
  688. // Return
  689. return $css;
  690. }
  691. /**
  692. * Create CSS style
  693. *
  694. * @param PHPExcel_Style $pStyle PHPExcel_Style
  695. * @return array
  696. */
  697. private function _createCSSStyle(PHPExcel_Style $pStyle) {
  698. // Construct CSS
  699. $css = '';
  700. // Create CSS
  701. $css = array_merge(
  702. $this->_createCSSStyleAlignment($pStyle->getAlignment())
  703. , $this->_createCSSStyleBorders($pStyle->getBorders())
  704. , $this->_createCSSStyleFont($pStyle->getFont())
  705. , $this->_createCSSStyleFill($pStyle->getFill())
  706. );
  707. // Return
  708. return $css;
  709. }
  710. /**
  711. * Create CSS style (PHPExcel_Style_Alignment)
  712. *
  713. * @param PHPExcel_Style_Alignment $pStyle PHPExcel_Style_Alignment
  714. * @return array
  715. */
  716. private function _createCSSStyleAlignment(PHPExcel_Style_Alignment $pStyle) {
  717. // Construct CSS
  718. $css = array();
  719. // Create CSS
  720. $css['vertical-align'] = $this->_mapVAlign($pStyle->getVertical());
  721. if ($textAlign = $this->_mapHAlign($pStyle->getHorizontal())) {
  722. $css['text-align'] = $textAlign;
  723. if(in_array($textAlign,array('left','right')))
  724. $css['padding-'.$textAlign] = (string)((int)$pStyle->getIndent() * 9).'px';
  725. }
  726. // Return
  727. return $css;
  728. }
  729. /**
  730. * Create CSS style (PHPExcel_Style_Font)
  731. *
  732. * @param PHPExcel_Style_Font $pStyle PHPExcel_Style_Font
  733. * @return array
  734. */
  735. private function _createCSSStyleFont(PHPExcel_Style_Font $pStyle) {
  736. // Construct CSS
  737. $css = array();
  738. // Create CSS
  739. if ($pStyle->getBold()) {
  740. $css['font-weight'] = 'bold';
  741. }
  742. if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
  743. $css['text-decoration'] = 'underline line-through';
  744. } else if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE) {
  745. $css['text-decoration'] = 'underline';
  746. } else if ($pStyle->getStrikethrough()) {
  747. $css['text-decoration'] = 'line-through';
  748. }
  749. if ($pStyle->getItalic()) {
  750. $css['font-style'] = 'italic';
  751. }
  752. $css['color'] = '#' . $pStyle->getColor()->getRGB();
  753. $css['font-family'] = '\'' . $pStyle->getName() . '\'';
  754. $css['font-size'] = $pStyle->getSize() . 'pt';
  755. // Return
  756. return $css;
  757. }
  758. /**
  759. * Create CSS style (PHPExcel_Style_Borders)
  760. *
  761. * @param PHPExcel_Style_Borders $pStyle PHPExcel_Style_Borders
  762. * @return array
  763. */
  764. private function _createCSSStyleBorders(PHPExcel_Style_Borders $pStyle) {
  765. // Construct CSS
  766. $css = array();
  767. // Create CSS
  768. $css['border-bottom'] = $this->_createCSSStyleBorder($pStyle->getBottom());
  769. $css['border-top'] = $this->_createCSSStyleBorder($pStyle->getTop());
  770. $css['border-left'] = $this->_createCSSStyleBorder($pStyle->getLeft());
  771. $css['border-right'] = $this->_createCSSStyleBorder($pStyle->getRight());
  772. // Return
  773. return $css;
  774. }
  775. /**
  776. * Create CSS style (PHPExcel_Style_Border)
  777. *
  778. * @param PHPExcel_Style_Border $pStyle PHPExcel_Style_Border
  779. * @return string
  780. */
  781. private function _createCSSStyleBorder(PHPExcel_Style_Border $pStyle) {
  782. // Create CSS
  783. $css = $this->_mapBorderStyle($pStyle->getBorderStyle()) . ' #' . $pStyle->getColor()->getRGB();
  784. // Return
  785. return $css;
  786. }
  787. /**
  788. * Create CSS style (PHPExcel_Style_Fill)
  789. *
  790. * @param PHPExcel_Style_Fill $pStyle PHPExcel_Style_Fill
  791. * @return array
  792. */
  793. private function _createCSSStyleFill(PHPExcel_Style_Fill $pStyle) {
  794. // Construct HTML
  795. $css = array();
  796. // Create CSS
  797. $value = $pStyle->getFillType() == PHPExcel_Style_Fill::FILL_NONE ?
  798. 'white' : '#' . $pStyle->getStartColor()->getRGB();
  799. $css['background-color'] = $value;
  800. // Return
  801. return $css;
  802. }
  803. /**
  804. * Generate HTML footer
  805. */
  806. public function generateHTMLFooter() {
  807. // Construct HTML
  808. $html = '';
  809. $html .= ' </body>' . PHP_EOL;
  810. $html .= '</html>' . PHP_EOL;
  811. // Return
  812. return $html;
  813. }
  814. /**
  815. * Generate table header
  816. *
  817. * @param PHPExcel_Worksheet $pSheet The worksheet for the table we are writing
  818. * @return string
  819. * @throws PHPExcel_Writer_Exception
  820. */
  821. private function _generateTableHeader($pSheet) {
  822. $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
  823. // Construct HTML
  824. $html = '';
  825. if (!$this->_useInlineCss) {
  826. $gridlines = $pSheet->getShowGridLines() ? ' gridlines' : '';
  827. $html .= ' <table border="0" cellpadding="0" cellspacing="0" id="sheet' . $sheetIndex . '" class="sheet' . $sheetIndex . $gridlines . '">' . PHP_EOL;
  828. } else {
  829. $style = isset($this->_cssStyles['table']) ?
  830. $this->_assembleCSS($this->_cssStyles['table']) : '';
  831. if ($this->_isPdf && $pSheet->getShowGridLines()) {
  832. $html .= ' <table border="1" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="4" style="' . $style . '">' . PHP_EOL;
  833. } else {
  834. $html .= ' <table border="0" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="4" style="' . $style . '">' . PHP_EOL;
  835. }
  836. }
  837. // Write <col> elements
  838. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) - 1;
  839. $i = -1;
  840. while($i++ < $highestColumnIndex) {
  841. if (!$this->_isPdf) {
  842. if (!$this->_useInlineCss) {
  843. $html .= ' <col class="col' . $i . '">' . PHP_EOL;
  844. } else {
  845. $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ?
  846. $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';
  847. $html .= ' <col style="' . $style . '">' . PHP_EOL;
  848. }
  849. }
  850. }
  851. // Return
  852. return $html;
  853. }
  854. /**
  855. * Generate table footer
  856. *
  857. * @throws PHPExcel_Writer_Exception
  858. */
  859. private function _generateTableFooter() {
  860. // Construct HTML
  861. $html = '';
  862. $html .= ' </table>' . PHP_EOL;
  863. // Return
  864. return $html;
  865. }
  866. /**
  867. * Generate row
  868. *
  869. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  870. * @param array $pValues Array containing cells in a row
  871. * @param int $pRow Row number (0-based)
  872. * @return string
  873. * @throws PHPExcel_Writer_Exception
  874. */
  875. private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0) {
  876. if (is_array($pValues)) {
  877. // Construct HTML
  878. $html = '';
  879. // Sheet index
  880. $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
  881. // DomPDF and breaks
  882. if ($this->_isPdf && count($pSheet->getBreaks()) > 0) {
  883. $breaks = $pSheet->getBreaks();
  884. // check if a break is needed before this row
  885. if (isset($breaks['A' . $pRow])) {
  886. // close table: </table>
  887. $html .= $this->_generateTableFooter();
  888. // insert page break
  889. $html .= '<div style="page-break-before:always" />';
  890. // open table again: <table> + <col> etc.
  891. $html .= $this->_generateTableHeader($pSheet);
  892. }
  893. }
  894. // Write row start
  895. if (!$this->_useInlineCss) {
  896. $html .= ' <tr class="row' . $pRow . '">' . PHP_EOL;
  897. } else {
  898. $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
  899. ? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
  900. $html .= ' <tr style="' . $style . '">' . PHP_EOL;
  901. }
  902. // Write cells
  903. $colNum = 0;
  904. foreach ($pValues as $cell) {
  905. $coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
  906. if (!$this->_useInlineCss) {
  907. $cssClass = '';
  908. $cssClass = 'column' . $colNum;
  909. } else {
  910. $cssClass = array();
  911. if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
  912. $this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
  913. }
  914. }
  915. $colSpan = 1;
  916. $rowSpan = 1;
  917. // initialize
  918. $cellData = '';
  919. // PHPExcel_Cell
  920. if ($cell instanceof PHPExcel_Cell) {
  921. if (is_null($cell->getParent())) {
  922. $cell->attach($pSheet);
  923. }
  924. // Value
  925. if ($cell->getValue() instanceof PHPExcel_RichText) {
  926. // Loop through rich text elements
  927. $elements = $cell->getValue()->getRichTextElements();
  928. foreach ($elements as $element) {
  929. // Rich text start?
  930. if ($element instanceof PHPExcel_RichText_Run) {
  931. $cellData .= '<span style="' . $this->_assembleCSS($this->_createCSSStyleFont($element->getFont())) . '">';
  932. if ($element->getFont()->getSuperScript()) {
  933. $cellData .= '<sup>';
  934. } else if ($element->getFont()->getSubScript()) {
  935. $cellData .= '<sub>';
  936. }
  937. }
  938. // Convert UTF8 data to PCDATA
  939. $cellText = $element->getText();
  940. $cellData .= htmlspecialchars($cellText);
  941. if ($element instanceof PHPExcel_RichText_Run) {
  942. if ($element->getFont()->getSuperScript()) {
  943. $cellData .= '</sup>';
  944. } else if ($element->getFont()->getSubScript()) {
  945. $cellData .= '</sub>';
  946. }
  947. $cellData .= '</span>';
  948. }
  949. }
  950. } else {
  951. if ($this->_preCalculateFormulas) {
  952. $cellData = PHPExcel_Style_NumberFormat::toFormattedString(
  953. $cell->getCalculatedValue(),
  954. $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
  955. array($this, 'formatColor')
  956. );
  957. } else {
  958. $cellData = PHPExcel_Style_NumberFormat::ToFormattedString(
  959. $cell->getValue(),
  960. $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
  961. array($this, 'formatColor')
  962. );
  963. }
  964. $cellData = htmlspecialchars($cellData);
  965. if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) {
  966. $cellData = '<sup>'.$cellData.'</sup>';
  967. } elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) {
  968. $cellData = '<sub>'.$cellData.'</sub>';
  969. }
  970. }
  971. // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
  972. // Example: " Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
  973. $cellData = preg_replace("/(?m)(?:^|\\G) /", '&nbsp;', $cellData);
  974. // convert newline "\n" to '<br>'
  975. $cellData = nl2br($cellData);
  976. // Extend CSS class?
  977. if (!$this->_useInlineCss) {
  978. $cssClass .= ' style' . $cell->getXfIndex();
  979. $cssClass .= ' ' . $cell->getDataType();
  980. } else {
  981. if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) {
  982. $cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]);
  983. }
  984. // General horizontal alignment: Actual horizontal alignment depends on dataType
  985. $sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() );
  986. if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL
  987. && isset($this->_cssStyles['.' . $cell->getDataType()]['text-align']))
  988. {
  989. $cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align'];
  990. }
  991. }
  992. }
  993. // Hyperlink?
  994. if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
  995. $cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip()) . '">' . $cellData . '</a>';
  996. }
  997. // Should the cell be written or is it swallowed by a rowspan or colspan?
  998. $writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
  999. && $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] );
  1000. // Colspan and Rowspan
  1001. $colspan = 1;
  1002. $rowspan = 1;
  1003. if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
  1004. $spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
  1005. $rowSpan = $spans['rowspan'];
  1006. $colSpan = $spans['colspan'];
  1007. }
  1008. // Write
  1009. if ($writeCell) {
  1010. // Column start
  1011. $html .= ' <td';
  1012. if (!$this->_useInlineCss) {
  1013. $html .= ' class="' . $cssClass . '"';
  1014. } else {
  1015. //** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
  1016. // We must explicitly write the width of the <td> element because TCPDF
  1017. // does not recognize e.g. <col style="width:42pt">
  1018. $width = 0;
  1019. $i = $colNum - 1;
  1020. $e = $colNum + $colSpan - 1;
  1021. while($i++ < $e) {
  1022. if (isset($this->_columnWidths[$sheetIndex][$i])) {
  1023. $width += $this->_columnWidths[$sheetIndex][$i];
  1024. }
  1025. }
  1026. $cssClass['width'] = $width . 'pt';
  1027. // We must also explicitly write the height of the <td> element because TCPDF
  1028. // does not recognize e.g. <tr style="height:50pt">
  1029. if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
  1030. $height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
  1031. $cssClass['height'] = $height;
  1032. }
  1033. //** end of redundant code **
  1034. $html .= ' style="' . $this->_assembleCSS($cssClass) . '"';
  1035. }
  1036. if ($colSpan > 1) {
  1037. $html .= ' colspan="' . $colSpan . '"';
  1038. }
  1039. if ($rowSpan > 1) {
  1040. $html .= ' rowspan="' . $rowSpan . '"';
  1041. }
  1042. $html .= '>';
  1043. // Image?
  1044. $html .= $this->_writeImageInCell($pSheet, $coordinate);
  1045. // Chart?
  1046. if ($this->_includeCharts) {
  1047. $html .= $this->_writeChartInCell($pSheet, $coordinate);
  1048. }
  1049. // Cell data
  1050. $html .= $cellData;
  1051. // Column end
  1052. $html .= '</td>' . PHP_EOL;
  1053. }
  1054. // Next column
  1055. ++$colNum;
  1056. }
  1057. // Write row end
  1058. $html .= ' </tr>' . PHP_EOL;
  1059. // Return
  1060. return $html;
  1061. } else {
  1062. throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
  1063. }
  1064. }
  1065. /**
  1066. * Takes array where of CSS properties / values and converts to CSS string
  1067. *
  1068. * @param array
  1069. * @return string
  1070. */
  1071. private function _assembleCSS($pValue = array())
  1072. {
  1073. $pairs = array();
  1074. foreach ($pValue as $property => $value) {
  1075. $pairs[] = $property . ':' . $value;
  1076. }
  1077. $string = implode('; ', $pairs);
  1078. return $string;
  1079. }
  1080. /**
  1081. * Get images root
  1082. *
  1083. * @return string
  1084. */
  1085. public function getImagesRoot() {
  1086. return $this->_imagesRoot;
  1087. }
  1088. /**
  1089. * Set images root
  1090. *
  1091. * @param string $pValue
  1092. * @return PHPExcel_Writer_HTML
  1093. */
  1094. public function setImagesRoot($pValue = '.') {
  1095. $this->_imagesRoot = $pValue;
  1096. return $this;
  1097. }
  1098. /**
  1099. * Get embed images
  1100. *
  1101. * @return boolean
  1102. */
  1103. public function getEmbedImages() {
  1104. return $this->_embedImages;
  1105. }
  1106. /**
  1107. * Set embed images
  1108. *
  1109. * @param boolean $pValue
  1110. * @return PHPExcel_Writer_HTML
  1111. */
  1112. public function setEmbedImages($pValue = '.') {
  1113. $this->_embedImages = $pValue;
  1114. return $this;
  1115. }
  1116. /**
  1117. * Get use inline CSS?
  1118. *
  1119. * @return boolean
  1120. */
  1121. public function getUseInlineCss() {
  1122. return $this->_useInlineCss;
  1123. }
  1124. /**
  1125. * Set use inline CSS?
  1126. *
  1127. * @param boolean $pValue
  1128. * @return PHPExcel_Writer_HTML
  1129. */
  1130. public function setUseInlineCss($pValue = false) {
  1131. $this->_useInlineCss = $pValue;
  1132. return $this;
  1133. }
  1134. /**
  1135. * Add color to formatted string as inline style
  1136. *
  1137. * @param string $pValue Plain formatted value without color
  1138. * @param string $pFormat Format code
  1139. * @return string
  1140. */
  1141. public function formatColor($pValue, $pFormat)
  1142. {
  1143. // Color information, e.g. [Red] is always at the beginning
  1144. $color = null; // initialize
  1145. $matches = array();
  1146. $color_regex = '/^\\[[a-zA-Z]+\\]/';
  1147. if (preg_match($color_regex, $pFormat, $matches)) {
  1148. $color = str_replace('[', '', $matches[0]);
  1149. $color = str_replace(']', '', $color);
  1150. $color = strtolower($color);
  1151. }
  1152. // convert to PCDATA
  1153. $value = htmlspecialchars($pValue);
  1154. // color span tag
  1155. if ($color !== null) {
  1156. $value = '<span style="color:' . $color . '">' . $value . '</span>';
  1157. }
  1158. return $value;
  1159. }
  1160. /**
  1161. * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
  1162. */
  1163. private function _calculateSpans()
  1164. {
  1165. // Identify all cells that should be omitted in HTML due to cell merge.
  1166. // In HTML only the upper-left cell should be written and it should have
  1167. // appropriate rowspan / colspan attribute
  1168. $sheetIndexes = $this->_sheetIndex !== null ?
  1169. array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1);
  1170. foreach ($sheetIndexes as $sheetIndex) {
  1171. $sheet = $this->_phpExcel->getSheet($sheetIndex);
  1172. $candidateSpannedRow = array();
  1173. // loop through all Excel merged cells
  1174. foreach ($sheet->getMergeCells() as $cells) {
  1175. list($cells, ) = PHPExcel_Cell::splitRange($cells);
  1176. $first = $cells[0];
  1177. $last = $cells[1];
  1178. list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first);
  1179. $fc = PHPExcel_Cell::columnIndexFromString($fc) - 1;
  1180. list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last);
  1181. $lc = PHPExcel_Cell::columnIndexFromString($lc) - 1;
  1182. // loop through the individual cells in the individual merge
  1183. $r = $fr - 1;
  1184. while($r++ < $lr) {
  1185. // also, flag this row as a HTML row that is candidate to be omitted
  1186. $candidateSpannedRow[$r] = $r;
  1187. $c = $fc - 1;
  1188. while($c++ < $lc) {
  1189. if ( !($c == $fc && $r == $fr) ) {
  1190. // not the upper-left cell (should not be written in HTML)
  1191. $this->_isSpannedCell[$sheetIndex][$r][$c] = array(
  1192. 'baseCell' => array($fr, $fc),
  1193. );
  1194. } else {
  1195. // upper-left is the base cell that should hold the colspan/rowspan attribute
  1196. $this->_isBaseCell[$sheetIndex][$r][$c] = array(
  1197. 'xlrowspan' => $lr - $fr + 1, // Excel rowspan
  1198. 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
  1199. 'xlcolspan' => $lc - $fc + 1, // Excel colspan
  1200. 'colspan' => $lc - $fc + 1, // HTML colspan, value may change
  1201. );
  1202. }
  1203. }
  1204. }
  1205. }
  1206. // Identify which rows should be omitted in HTML. These are the rows where all the cells
  1207. // participate in a merge and the where base cells are somewhere above.
  1208. $countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
  1209. foreach ($candidateSpannedRow as $rowIndex) {
  1210. if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) {
  1211. if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
  1212. $this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
  1213. };
  1214. }
  1215. }
  1216. // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
  1217. if ( isset($this->_isSpannedRow[$sheetIndex]) ) {
  1218. foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) {
  1219. $adjustedBaseCells = array();
  1220. $c = -1;
  1221. $e = $countColumns - 1;
  1222. while($c++ < $e) {
  1223. $baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
  1224. if ( !in_array($baseCell, $adjustedBaseCells) ) {
  1225. // subtract rowspan by 1
  1226. --$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
  1227. $adjustedBaseCells[] = $baseCell;
  1228. }
  1229. }
  1230. }
  1231. }
  1232. // TODO: Same for columns
  1233. }
  1234. // We have calculated the spans
  1235. $this->_spansAreCalculated = true;
  1236. }
  1237. }