PageRenderTime 68ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/app/lib/core/Parsers/PHPExcel/PHPExcel/Writer/HTML.php

https://github.com/libis/providencelibiscode
PHP | 1498 lines | 809 code | 208 blank | 481 comment | 172 complexity | 44ca760724ce8c72e19c89f4245b2b71 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, GPL-3.0, LGPL-2.0, LGPL-3.0
  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. $html .= $this->_extendRowsForChartsAndImages($sheet, $row);
  397. // Write table footer
  398. $html .= $this->_generateTableFooter();
  399. // Writing PDF?
  400. if ($this->_isPdf) {
  401. if (is_null($this->_sheetIndex) && $sheetId + 1 < $this->_phpExcel->getSheetCount()) {
  402. $html .= '<div style="page-break-before:always" />';
  403. }
  404. }
  405. // Next sheet
  406. ++$sheetId;
  407. }
  408. // Return
  409. return $html;
  410. }
  411. /**
  412. * Generate sheet tabs
  413. *
  414. * @return string
  415. * @throws PHPExcel_Writer_Exception
  416. */
  417. public function generateNavigation()
  418. {
  419. // PHPExcel object known?
  420. if (is_null($this->_phpExcel)) {
  421. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  422. }
  423. // Fetch sheets
  424. $sheets = array();
  425. if (is_null($this->_sheetIndex)) {
  426. $sheets = $this->_phpExcel->getAllSheets();
  427. } else {
  428. $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
  429. }
  430. // Construct HTML
  431. $html = '';
  432. // Only if there are more than 1 sheets
  433. if (count($sheets) > 1) {
  434. // Loop all sheets
  435. $sheetId = 0;
  436. $html .= '<ul class="navigation">' . PHP_EOL;
  437. foreach ($sheets as $sheet) {
  438. $html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL;
  439. ++$sheetId;
  440. }
  441. $html .= '</ul>' . PHP_EOL;
  442. }
  443. return $html;
  444. }
  445. private function _extendRowsForChartsAndImages(PHPExcel_Worksheet $pSheet, $row) {
  446. $rowMax = $row;
  447. $colMax = 'A';
  448. if ($this->_includeCharts) {
  449. foreach ($pSheet->getChartCollection() as $chart) {
  450. if ($chart instanceof PHPExcel_Chart) {
  451. $chartCoordinates = $chart->getTopLeftPosition();
  452. $chartTL = PHPExcel_Cell::coordinateFromString($chartCoordinates['cell']);
  453. $chartCol = PHPExcel_Cell::columnIndexFromString($chartTL[0]);
  454. if ($chartTL[1] > $rowMax) {
  455. $rowMax = $chartTL[1];
  456. }
  457. if ($chartCol > PHPExcel_Cell::columnIndexFromString($colMax)) {
  458. $colMax = $chartTL[0];
  459. }
  460. }
  461. }
  462. }
  463. foreach ($pSheet->getDrawingCollection() as $drawing) {
  464. if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
  465. $imageTL = PHPExcel_Cell::coordinateFromString($drawing->getCoordinates());
  466. $imageCol = PHPExcel_Cell::columnIndexFromString($imageTL[0]);
  467. if ($imageTL[1] > $rowMax) {
  468. $rowMax = $imageTL[1];
  469. }
  470. if ($imageCol > PHPExcel_Cell::columnIndexFromString($colMax)) {
  471. $colMax = $imageTL[0];
  472. }
  473. }
  474. }
  475. $html = '';
  476. $colMax++;
  477. while ($row <= $rowMax) {
  478. $html .= '<tr>';
  479. for ($col = 'A'; $col != $colMax; ++$col) {
  480. $html .= '<td>';
  481. $html .= $this->_writeImageInCell($pSheet, $col.$row);
  482. if ($this->_includeCharts) {
  483. $html .= $this->_writeChartInCell($pSheet, $col.$row);
  484. }
  485. $html .= '</td>';
  486. }
  487. ++$row;
  488. $html .= '</tr>';
  489. }
  490. return $html;
  491. }
  492. /**
  493. * Generate image tag in cell
  494. *
  495. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  496. * @param string $coordinates Cell coordinates
  497. * @return string
  498. * @throws PHPExcel_Writer_Exception
  499. */
  500. private function _writeImageInCell(PHPExcel_Worksheet $pSheet, $coordinates) {
  501. // Construct HTML
  502. $html = '';
  503. // Write images
  504. foreach ($pSheet->getDrawingCollection() as $drawing) {
  505. if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
  506. if ($drawing->getCoordinates() == $coordinates) {
  507. $filename = $drawing->getPath();
  508. // Strip off eventual '.'
  509. if (substr($filename, 0, 1) == '.') {
  510. $filename = substr($filename, 1);
  511. }
  512. // Prepend images root
  513. $filename = $this->getImagesRoot() . $filename;
  514. // Strip off eventual '.'
  515. if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
  516. $filename = substr($filename, 1);
  517. }
  518. // Convert UTF8 data to PCDATA
  519. $filename = htmlspecialchars($filename);
  520. $html .= PHP_EOL;
  521. if ((!$this->_embedImages) || ($this->_isPdf)) {
  522. $imageData = $filename;
  523. } else {
  524. $imageDetails = getimagesize($filename);
  525. if ($fp = fopen($filename,"rb", 0)) {
  526. $picture = fread($fp,filesize($filename));
  527. fclose($fp);
  528. // base64 encode the binary data, then break it
  529. // into chunks according to RFC 2045 semantics
  530. $base64 = chunk_split(base64_encode($picture));
  531. $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
  532. } else {
  533. $imageData = $filename;
  534. }
  535. }
  536. $html .= '<div style="position: relative;">';
  537. $html .= '<img style="position: absolute; z-index: 1; left: ' . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' . $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . $imageData . '" border="0" />' . PHP_EOL;
  538. $html .= '</div>';
  539. }
  540. }
  541. }
  542. // Return
  543. return $html;
  544. }
  545. /**
  546. * Generate chart tag in cell
  547. *
  548. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  549. * @param string $coordinates Cell coordinates
  550. * @return string
  551. * @throws PHPExcel_Writer_Exception
  552. */
  553. private function _writeChartInCell(PHPExcel_Worksheet $pSheet, $coordinates) {
  554. // Construct HTML
  555. $html = '';
  556. // Write charts
  557. foreach ($pSheet->getChartCollection() as $chart) {
  558. if ($chart instanceof PHPExcel_Chart) {
  559. $chartCoordinates = $chart->getTopLeftPosition();
  560. if ($chartCoordinates['cell'] == $coordinates) {
  561. $chartFileName = PHPExcel_Shared_File::sys_get_temp_dir().'/'.uniqid().'.png';
  562. if (!$chart->render($chartFileName)) {
  563. return;
  564. }
  565. $html .= PHP_EOL;
  566. $imageDetails = getimagesize($chartFileName);
  567. if ($fp = fopen($chartFileName,"rb", 0)) {
  568. $picture = fread($fp,filesize($chartFileName));
  569. fclose($fp);
  570. // base64 encode the binary data, then break it
  571. // into chunks according to RFC 2045 semantics
  572. $base64 = chunk_split(base64_encode($picture));
  573. $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
  574. $html .= '<div style="position: relative;">';
  575. $html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" border="0" />' . PHP_EOL;
  576. $html .= '</div>';
  577. unlink($chartFileName);
  578. }
  579. }
  580. }
  581. }
  582. // Return
  583. return $html;
  584. }
  585. /**
  586. * Generate CSS styles
  587. *
  588. * @param boolean $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>)
  589. * @return string
  590. * @throws PHPExcel_Writer_Exception
  591. */
  592. public function generateStyles($generateSurroundingHTML = true) {
  593. // PHPExcel object known?
  594. if (is_null($this->_phpExcel)) {
  595. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  596. }
  597. // Build CSS
  598. $css = $this->buildCSS($generateSurroundingHTML);
  599. // Construct HTML
  600. $html = '';
  601. // Start styles
  602. if ($generateSurroundingHTML) {
  603. $html .= ' <style type="text/css">' . PHP_EOL;
  604. $html .= ' html { ' . $this->_assembleCSS($css['html']) . ' }' . PHP_EOL;
  605. }
  606. // Write all other styles
  607. foreach ($css as $styleName => $styleDefinition) {
  608. if ($styleName != 'html') {
  609. $html .= ' ' . $styleName . ' { ' . $this->_assembleCSS($styleDefinition) . ' }' . PHP_EOL;
  610. }
  611. }
  612. // End styles
  613. if ($generateSurroundingHTML) {
  614. $html .= ' </style>' . PHP_EOL;
  615. }
  616. // Return
  617. return $html;
  618. }
  619. /**
  620. * Build CSS styles
  621. *
  622. * @param boolean $generateSurroundingHTML Generate surrounding HTML style? (html { })
  623. * @return array
  624. * @throws PHPExcel_Writer_Exception
  625. */
  626. public function buildCSS($generateSurroundingHTML = true) {
  627. // PHPExcel object known?
  628. if (is_null($this->_phpExcel)) {
  629. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  630. }
  631. // Cached?
  632. if (!is_null($this->_cssStyles)) {
  633. return $this->_cssStyles;
  634. }
  635. // Ensure that spans have been calculated
  636. if (!$this->_spansAreCalculated) {
  637. $this->_calculateSpans();
  638. }
  639. // Construct CSS
  640. $css = array();
  641. // Start styles
  642. if ($generateSurroundingHTML) {
  643. // html { }
  644. $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif';
  645. $css['html']['font-size'] = '11pt';
  646. $css['html']['background-color'] = 'white';
  647. }
  648. // table { }
  649. $css['table']['border-collapse'] = 'collapse';
  650. if (!$this->_isPdf) {
  651. $css['table']['page-break-after'] = 'always';
  652. }
  653. // .gridlines td { }
  654. $css['.gridlines td']['border'] = '1px dotted black';
  655. // .b {}
  656. $css['.b']['text-align'] = 'center'; // BOOL
  657. // .e {}
  658. $css['.e']['text-align'] = 'center'; // ERROR
  659. // .f {}
  660. $css['.f']['text-align'] = 'right'; // FORMULA
  661. // .inlineStr {}
  662. $css['.inlineStr']['text-align'] = 'left'; // INLINE
  663. // .n {}
  664. $css['.n']['text-align'] = 'right'; // NUMERIC
  665. // .s {}
  666. $css['.s']['text-align'] = 'left'; // STRING
  667. // Calculate cell style hashes
  668. foreach ($this->_phpExcel->getCellXfCollection() as $index => $style) {
  669. $css['td.style' . $index] = $this->_createCSSStyle( $style );
  670. }
  671. // Fetch sheets
  672. $sheets = array();
  673. if (is_null($this->_sheetIndex)) {
  674. $sheets = $this->_phpExcel->getAllSheets();
  675. } else {
  676. $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
  677. }
  678. // Build styles per sheet
  679. foreach ($sheets as $sheet) {
  680. // Calculate hash code
  681. $sheetIndex = $sheet->getParent()->getIndex($sheet);
  682. // Build styles
  683. // Calculate column widths
  684. $sheet->calculateColumnWidths();
  685. // col elements, initialize
  686. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) - 1;
  687. $column = -1;
  688. while($column++ < $highestColumnIndex) {
  689. $this->_columnWidths[$sheetIndex][$column] = 42; // approximation
  690. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt';
  691. }
  692. // col elements, loop through columnDimensions and set width
  693. foreach ($sheet->getColumnDimensions() as $columnDimension) {
  694. if (($width = PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth(), $this->_defaultFont)) >= 0) {
  695. $width = PHPExcel_Shared_Drawing::pixelsToPoints($width);
  696. $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1;
  697. $this->_columnWidths[$sheetIndex][$column] = $width;
  698. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt';
  699. if ($columnDimension->getVisible() === false) {
  700. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse';
  701. $css['table.sheet' . $sheetIndex . ' col.col' . $column]['*display'] = 'none'; // target IE6+7
  702. }
  703. }
  704. }
  705. // Default row height
  706. $rowDimension = $sheet->getDefaultRowDimension();
  707. // table.sheetN tr { }
  708. $css['table.sheet' . $sheetIndex . ' tr'] = array();
  709. if ($rowDimension->getRowHeight() == -1) {
  710. $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont());
  711. } else {
  712. $pt_height = $rowDimension->getRowHeight();
  713. }
  714. $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt';
  715. if ($rowDimension->getVisible() === false) {
  716. $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none';
  717. $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden';
  718. }
  719. // Calculate row heights
  720. foreach ($sheet->getRowDimensions() as $rowDimension) {
  721. $row = $rowDimension->getRowIndex() - 1;
  722. // table.sheetN tr.rowYYYYYY { }
  723. $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = array();
  724. if ($rowDimension->getRowHeight() == -1) {
  725. $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont());
  726. } else {
  727. $pt_height = $rowDimension->getRowHeight();
  728. }
  729. $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt';
  730. if ($rowDimension->getVisible() === false) {
  731. $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none';
  732. $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden';
  733. }
  734. }
  735. }
  736. // Cache
  737. if (is_null($this->_cssStyles)) {
  738. $this->_cssStyles = $css;
  739. }
  740. // Return
  741. return $css;
  742. }
  743. /**
  744. * Create CSS style
  745. *
  746. * @param PHPExcel_Style $pStyle PHPExcel_Style
  747. * @return array
  748. */
  749. private function _createCSSStyle(PHPExcel_Style $pStyle) {
  750. // Construct CSS
  751. $css = '';
  752. // Create CSS
  753. $css = array_merge(
  754. $this->_createCSSStyleAlignment($pStyle->getAlignment())
  755. , $this->_createCSSStyleBorders($pStyle->getBorders())
  756. , $this->_createCSSStyleFont($pStyle->getFont())
  757. , $this->_createCSSStyleFill($pStyle->getFill())
  758. );
  759. // Return
  760. return $css;
  761. }
  762. /**
  763. * Create CSS style (PHPExcel_Style_Alignment)
  764. *
  765. * @param PHPExcel_Style_Alignment $pStyle PHPExcel_Style_Alignment
  766. * @return array
  767. */
  768. private function _createCSSStyleAlignment(PHPExcel_Style_Alignment $pStyle) {
  769. // Construct CSS
  770. $css = array();
  771. // Create CSS
  772. $css['vertical-align'] = $this->_mapVAlign($pStyle->getVertical());
  773. if ($textAlign = $this->_mapHAlign($pStyle->getHorizontal())) {
  774. $css['text-align'] = $textAlign;
  775. if(in_array($textAlign,array('left','right')))
  776. $css['padding-'.$textAlign] = (string)((int)$pStyle->getIndent() * 9).'px';
  777. }
  778. // Return
  779. return $css;
  780. }
  781. /**
  782. * Create CSS style (PHPExcel_Style_Font)
  783. *
  784. * @param PHPExcel_Style_Font $pStyle PHPExcel_Style_Font
  785. * @return array
  786. */
  787. private function _createCSSStyleFont(PHPExcel_Style_Font $pStyle) {
  788. // Construct CSS
  789. $css = array();
  790. // Create CSS
  791. if ($pStyle->getBold()) {
  792. $css['font-weight'] = 'bold';
  793. }
  794. if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
  795. $css['text-decoration'] = 'underline line-through';
  796. } else if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE) {
  797. $css['text-decoration'] = 'underline';
  798. } else if ($pStyle->getStrikethrough()) {
  799. $css['text-decoration'] = 'line-through';
  800. }
  801. if ($pStyle->getItalic()) {
  802. $css['font-style'] = 'italic';
  803. }
  804. $css['color'] = '#' . $pStyle->getColor()->getRGB();
  805. $css['font-family'] = '\'' . $pStyle->getName() . '\'';
  806. $css['font-size'] = $pStyle->getSize() . 'pt';
  807. // Return
  808. return $css;
  809. }
  810. /**
  811. * Create CSS style (PHPExcel_Style_Borders)
  812. *
  813. * @param PHPExcel_Style_Borders $pStyle PHPExcel_Style_Borders
  814. * @return array
  815. */
  816. private function _createCSSStyleBorders(PHPExcel_Style_Borders $pStyle) {
  817. // Construct CSS
  818. $css = array();
  819. // Create CSS
  820. $css['border-bottom'] = $this->_createCSSStyleBorder($pStyle->getBottom());
  821. $css['border-top'] = $this->_createCSSStyleBorder($pStyle->getTop());
  822. $css['border-left'] = $this->_createCSSStyleBorder($pStyle->getLeft());
  823. $css['border-right'] = $this->_createCSSStyleBorder($pStyle->getRight());
  824. // Return
  825. return $css;
  826. }
  827. /**
  828. * Create CSS style (PHPExcel_Style_Border)
  829. *
  830. * @param PHPExcel_Style_Border $pStyle PHPExcel_Style_Border
  831. * @return string
  832. */
  833. private function _createCSSStyleBorder(PHPExcel_Style_Border $pStyle) {
  834. // Create CSS
  835. $css = $this->_mapBorderStyle($pStyle->getBorderStyle()) . ' #' . $pStyle->getColor()->getRGB();
  836. // Return
  837. return $css;
  838. }
  839. /**
  840. * Create CSS style (PHPExcel_Style_Fill)
  841. *
  842. * @param PHPExcel_Style_Fill $pStyle PHPExcel_Style_Fill
  843. * @return array
  844. */
  845. private function _createCSSStyleFill(PHPExcel_Style_Fill $pStyle) {
  846. // Construct HTML
  847. $css = array();
  848. // Create CSS
  849. $value = $pStyle->getFillType() == PHPExcel_Style_Fill::FILL_NONE ?
  850. 'white' : '#' . $pStyle->getStartColor()->getRGB();
  851. $css['background-color'] = $value;
  852. // Return
  853. return $css;
  854. }
  855. /**
  856. * Generate HTML footer
  857. */
  858. public function generateHTMLFooter() {
  859. // Construct HTML
  860. $html = '';
  861. $html .= ' </body>' . PHP_EOL;
  862. $html .= '</html>' . PHP_EOL;
  863. // Return
  864. return $html;
  865. }
  866. /**
  867. * Generate table header
  868. *
  869. * @param PHPExcel_Worksheet $pSheet The worksheet for the table we are writing
  870. * @return string
  871. * @throws PHPExcel_Writer_Exception
  872. */
  873. private function _generateTableHeader($pSheet) {
  874. $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
  875. // Construct HTML
  876. $html = '';
  877. if (!$this->_useInlineCss) {
  878. $gridlines = $pSheet->getShowGridLines() ? ' gridlines' : '';
  879. $html .= ' <table border="0" cellpadding="0" cellspacing="0" id="sheet' . $sheetIndex . '" class="sheet' . $sheetIndex . $gridlines . '">' . PHP_EOL;
  880. } else {
  881. $style = isset($this->_cssStyles['table']) ?
  882. $this->_assembleCSS($this->_cssStyles['table']) : '';
  883. if ($this->_isPdf && $pSheet->getShowGridLines()) {
  884. $html .= ' <table border="1" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="1" style="' . $style . '">' . PHP_EOL;
  885. } else {
  886. $html .= ' <table border="0" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="0" style="' . $style . '">' . PHP_EOL;
  887. }
  888. }
  889. // Write <col> elements
  890. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) - 1;
  891. $i = -1;
  892. while($i++ < $highestColumnIndex) {
  893. if (!$this->_isPdf) {
  894. if (!$this->_useInlineCss) {
  895. $html .= ' <col class="col' . $i . '">' . PHP_EOL;
  896. } else {
  897. $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ?
  898. $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';
  899. $html .= ' <col style="' . $style . '">' . PHP_EOL;
  900. }
  901. }
  902. }
  903. // Return
  904. return $html;
  905. }
  906. /**
  907. * Generate table footer
  908. *
  909. * @throws PHPExcel_Writer_Exception
  910. */
  911. private function _generateTableFooter() {
  912. // Construct HTML
  913. $html = '';
  914. $html .= ' </table>' . PHP_EOL;
  915. // Return
  916. return $html;
  917. }
  918. /**
  919. * Generate row
  920. *
  921. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  922. * @param array $pValues Array containing cells in a row
  923. * @param int $pRow Row number (0-based)
  924. * @return string
  925. * @throws PHPExcel_Writer_Exception
  926. */
  927. private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0) {
  928. if (is_array($pValues)) {
  929. // Construct HTML
  930. $html = '';
  931. // Sheet index
  932. $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
  933. // DomPDF and breaks
  934. if ($this->_isPdf && count($pSheet->getBreaks()) > 0) {
  935. $breaks = $pSheet->getBreaks();
  936. // check if a break is needed before this row
  937. if (isset($breaks['A' . $pRow])) {
  938. // close table: </table>
  939. $html .= $this->_generateTableFooter();
  940. // insert page break
  941. $html .= '<div style="page-break-before:always" />';
  942. // open table again: <table> + <col> etc.
  943. $html .= $this->_generateTableHeader($pSheet);
  944. }
  945. }
  946. // Write row start
  947. if (!$this->_useInlineCss) {
  948. $html .= ' <tr class="row' . $pRow . '">' . PHP_EOL;
  949. } else {
  950. $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
  951. ? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
  952. $html .= ' <tr style="' . $style . '">' . PHP_EOL;
  953. }
  954. // Write cells
  955. $colNum = 0;
  956. foreach ($pValues as $cell) {
  957. $coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
  958. if (!$this->_useInlineCss) {
  959. $cssClass = '';
  960. $cssClass = 'column' . $colNum;
  961. } else {
  962. $cssClass = array();
  963. if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
  964. $this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
  965. }
  966. }
  967. $colSpan = 1;
  968. $rowSpan = 1;
  969. // initialize
  970. $cellData = '&nbsp;';
  971. // PHPExcel_Cell
  972. if ($cell instanceof PHPExcel_Cell) {
  973. $cellData = '';
  974. if (is_null($cell->getParent())) {
  975. $cell->attach($pSheet);
  976. }
  977. // Value
  978. if ($cell->getValue() instanceof PHPExcel_RichText) {
  979. // Loop through rich text elements
  980. $elements = $cell->getValue()->getRichTextElements();
  981. foreach ($elements as $element) {
  982. // Rich text start?
  983. if ($element instanceof PHPExcel_RichText_Run) {
  984. $cellData .= '<span style="' . $this->_assembleCSS($this->_createCSSStyleFont($element->getFont())) . '">';
  985. if ($element->getFont()->getSuperScript()) {
  986. $cellData .= '<sup>';
  987. } else if ($element->getFont()->getSubScript()) {
  988. $cellData .= '<sub>';
  989. }
  990. }
  991. // Convert UTF8 data to PCDATA
  992. $cellText = $element->getText();
  993. $cellData .= htmlspecialchars($cellText);
  994. if ($element instanceof PHPExcel_RichText_Run) {
  995. if ($element->getFont()->getSuperScript()) {
  996. $cellData .= '</sup>';
  997. } else if ($element->getFont()->getSubScript()) {
  998. $cellData .= '</sub>';
  999. }
  1000. $cellData .= '</span>';
  1001. }
  1002. }
  1003. } else {
  1004. if ($this->_preCalculateFormulas) {
  1005. $cellData = PHPExcel_Style_NumberFormat::toFormattedString(
  1006. $cell->getCalculatedValue(),
  1007. $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
  1008. array($this, 'formatColor')
  1009. );
  1010. } else {
  1011. $cellData = PHPExcel_Style_NumberFormat::ToFormattedString(
  1012. $cell->getValue(),
  1013. $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
  1014. array($this, 'formatColor')
  1015. );
  1016. }
  1017. $cellData = htmlspecialchars($cellData);
  1018. if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) {
  1019. $cellData = '<sup>'.$cellData.'</sup>';
  1020. } elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) {
  1021. $cellData = '<sub>'.$cellData.'</sub>';
  1022. }
  1023. }
  1024. // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
  1025. // Example: " Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
  1026. $cellData = preg_replace("/(?m)(?:^|\\G) /", '&nbsp;', $cellData);
  1027. // convert newline "\n" to '<br>'
  1028. $cellData = nl2br($cellData);
  1029. // Extend CSS class?
  1030. if (!$this->_useInlineCss) {
  1031. $cssClass .= ' style' . $cell->getXfIndex();
  1032. $cssClass .= ' ' . $cell->getDataType();
  1033. } else {
  1034. if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) {
  1035. $cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]);
  1036. }
  1037. // General horizontal alignment: Actual horizontal alignment depends on dataType
  1038. $sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() );
  1039. if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL
  1040. && isset($this->_cssStyles['.' . $cell->getDataType()]['text-align']))
  1041. {
  1042. $cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align'];
  1043. }
  1044. }
  1045. }
  1046. // Hyperlink?
  1047. if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
  1048. $cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip()) . '">' . $cellData . '</a>';
  1049. }
  1050. // Should the cell be written or is it swallowed by a rowspan or colspan?
  1051. $writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
  1052. && $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] );
  1053. // Colspan and Rowspan
  1054. $colspan = 1;
  1055. $rowspan = 1;
  1056. if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
  1057. $spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
  1058. $rowSpan = $spans['rowspan'];
  1059. $colSpan = $spans['colspan'];
  1060. }
  1061. // Write
  1062. if ($writeCell) {
  1063. // Column start
  1064. $html .= ' <td';
  1065. if (!$this->_useInlineCss) {
  1066. $html .= ' class="' . $cssClass . '"';
  1067. } else {
  1068. //** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
  1069. // We must explicitly write the width of the <td> element because TCPDF
  1070. // does not recognize e.g. <col style="width:42pt">
  1071. $width = 0;
  1072. $i = $colNum - 1;
  1073. $e = $colNum + $colSpan - 1;
  1074. while($i++ < $e) {
  1075. if (isset($this->_columnWidths[$sheetIndex][$i])) {
  1076. $width += $this->_columnWidths[$sheetIndex][$i];
  1077. }
  1078. }
  1079. $cssClass['width'] = $width . 'pt';
  1080. // We must also explicitly write the height of the <td> element because TCPDF
  1081. // does not recognize e.g. <tr style="height:50pt">
  1082. if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
  1083. $height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
  1084. $cssClass['height'] = $height;
  1085. }
  1086. //** end of redundant code **
  1087. $html .= ' style="' . $this->_assembleCSS($cssClass) . '"';
  1088. }
  1089. if ($colSpan > 1) {
  1090. $html .= ' colspan="' . $colSpan . '"';
  1091. }
  1092. if ($rowSpan > 1) {
  1093. $html .= ' rowspan="' . $rowSpan . '"';
  1094. }
  1095. $html .= '>';
  1096. // Image?
  1097. $html .= $this->_writeImageInCell($pSheet, $coordinate);
  1098. // Chart?
  1099. if ($this->_includeCharts) {
  1100. $html .= $this->_writeChartInCell($pSheet, $coordinate);
  1101. }
  1102. // Cell data
  1103. $html .= $cellData;
  1104. // Column end
  1105. $html .= '</td>' . PHP_EOL;
  1106. }
  1107. // Next column
  1108. ++$colNum;
  1109. }
  1110. // Write row end
  1111. $html .= ' </tr>' . PHP_EOL;
  1112. // Return
  1113. return $html;
  1114. } else {
  1115. throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
  1116. }
  1117. }
  1118. /**
  1119. * Takes array where of CSS properties / values and converts to CSS string
  1120. *
  1121. * @param array
  1122. * @return string
  1123. */
  1124. private function _assembleCSS($pValue = array())
  1125. {
  1126. $pairs = array();
  1127. foreach ($pValue as $property => $value) {
  1128. $pairs[] = $property . ':' . $value;
  1129. }
  1130. $string = implode('; ', $pairs);
  1131. return $string;
  1132. }
  1133. /**
  1134. * Get images root
  1135. *
  1136. * @return string
  1137. */
  1138. public function getImagesRoot() {
  1139. return $this->_imagesRoot;
  1140. }
  1141. /**
  1142. * Set images root
  1143. *
  1144. * @param string $pValue
  1145. * @return PHPExcel_Writer_HTML
  1146. */
  1147. public function setImagesRoot($pValue = '.') {
  1148. $this->_imagesRoot = $pValue;
  1149. return $this;
  1150. }
  1151. /**
  1152. * Get embed images
  1153. *
  1154. * @return boolean
  1155. */
  1156. public function getEmbedImages() {
  1157. return $this->_embedImages;
  1158. }
  1159. /**
  1160. * Set embed images
  1161. *
  1162. * @param boolean $pValue
  1163. * @return PHPExcel_Writer_HTML
  1164. */
  1165. public function setEmbedImages($pValue = '.') {
  1166. $this->_embedImages = $pValue;
  1167. return $this;
  1168. }
  1169. /**
  1170. * Get use inline CSS?
  1171. *
  1172. * @return boolean
  1173. */
  1174. public function getUseInlineCss() {
  1175. return $this->_useInlineCss;
  1176. }
  1177. /**
  1178. * Set use inline CSS?
  1179. *
  1180. * @param boolean $pValue
  1181. * @return PHPExcel_Writer_HTML
  1182. */
  1183. public function setUseInlineCss($pValue = false) {
  1184. $this->_useInlineCss = $pValue;
  1185. return $this;
  1186. }
  1187. /**
  1188. * Add color to formatted string as inline style
  1189. *
  1190. * @param string $pValue Plain formatted value without color
  1191. * @param string $pFormat Format code
  1192. * @return string
  1193. */
  1194. public function formatColor($pValue, $pFormat)
  1195. {
  1196. // Color information, e.g. [Red] is always at the beginning
  1197. $color = null; // initialize
  1198. $matches = array();
  1199. $color_regex = '/^\\[[a-zA-Z]+\\]/';
  1200. if (preg_match($color_regex, $pFormat, $matches)) {
  1201. $color = str_replace('[', '', $matches[0]);
  1202. $color = str_replace(']', '', $color);
  1203. $color = strtolower($color);
  1204. }
  1205. // convert to PCDATA
  1206. $value = htmlspecialchars($pValue);
  1207. // color span tag
  1208. if ($color !== null) {
  1209. $value = '<span style="color:' . $color . '">' . $value . '</span>';
  1210. }
  1211. return $value;
  1212. }
  1213. /**
  1214. * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
  1215. */
  1216. private function _calculateSpans()
  1217. {
  1218. // Identify all cells that should be omitted in HTML due to cell merge.
  1219. // In HTML only the upper-left cell should be written and it should have
  1220. // appropriate rowspan / colspan attribute
  1221. $sheetIndexes = $this->_sheetIndex !== null ?
  1222. array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1);
  1223. foreach ($sheetIndexes as $sheetIndex) {
  1224. $sheet = $this->_phpExcel->getSheet($sheetIndex);
  1225. $candidateSpannedRow = array();
  1226. // loop through all Excel merged cells
  1227. foreach ($sheet->getMergeCells() as $cells) {
  1228. list($cells, ) = PHPExcel_Cell::splitRange($cells);
  1229. $first = $cells[0];
  1230. $last = $cells[1];
  1231. list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first);
  1232. $fc = PHPExcel_Cell::columnIndexFromString($fc) - 1;
  1233. list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last);
  1234. $lc = PHPExcel_Cell::columnIndexFromString($lc) - 1;
  1235. // loop through the individual cells in the individual merge
  1236. $r = $fr - 1;
  1237. while($r++ < $lr) {
  1238. // also, flag this row as a HTML row that is candidate to be omitted
  1239. $candidateSpannedRow[$r] = $r;
  1240. $c = $fc - 1;
  1241. while($c++ < $lc) {
  1242. if ( !($c == $fc && $r == $fr) ) {
  1243. // not the upper-left cell (should not be written in HTML)
  1244. $this->_isSpannedCell[$sheetIndex][$r][$c] = array(
  1245. 'baseCell' => array($fr, $fc),
  1246. );
  1247. } else {
  1248. // upper-left is the base cell that should hold the colspan/rowspan attribute
  1249. $this->_isBaseCell[$sheetIndex][$r][$c] = array(
  1250. 'xlrowspan' => $lr - $fr + 1, // Excel rowspan
  1251. 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
  1252. 'xlcolspan' => $lc - $fc + 1, // Excel colspan
  1253. 'colspan' => $lc - $fc + 1, // HTML colspan, value may change
  1254. );
  1255. }
  1256. }
  1257. }
  1258. }
  1259. // Identify which rows should be omitted in HTML. These are the rows where all the cells
  1260. // participate in a merge and the where base cells are somewhere above.
  1261. $countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
  1262. foreach ($candidateSpannedRow as $rowIndex) {
  1263. if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) {
  1264. if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
  1265. $this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
  1266. };
  1267. }
  1268. }
  1269. // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
  1270. if ( isset($this->_isSpannedRow[$sheetIndex]) ) {
  1271. foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) {
  1272. $adjustedBaseCells = array();
  1273. $c = -1;
  1274. $e = $countColumns - 1;
  1275. while($c++ < $e) {
  1276. $baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
  1277. if ( !in_array($baseCell, $adjustedBaseCells) ) {
  1278. // subtract rowspan by 1
  1279. --$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
  1280. $adjustedBaseCells[] = $baseCell;
  1281. }
  1282. }
  1283. }
  1284. }
  1285. // TODO: Same for columns
  1286. }
  1287. // We have calculated the spans
  1288. $this->_spansAreCalculated = true;
  1289. }
  1290. }