HTML.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2014 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Writer_HTML
  23. * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version 1.8.0, 2014-03-02
  26. */
  27. /**
  28. * PHPExcel_Writer_HTML
  29. *
  30. * @category PHPExcel
  31. * @package PHPExcel_Writer_HTML
  32. * @copyright Copyright (c) 2006 - 2014 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($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
  138. PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(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($this->_phpExcel)->getDebugLog()->setWriteDebugLog($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. $theadStart = $theadEnd = 0; // default: no <thead> no </thead>
  350. if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
  351. $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();
  352. // we can only support repeating rows that start at top row
  353. if ($rowsToRepeatAtTop[0] == 1) {
  354. $theadStart = $rowsToRepeatAtTop[0];
  355. $theadEnd = $rowsToRepeatAtTop[1];
  356. $tbodyStart = $rowsToRepeatAtTop[1] + 1;
  357. }
  358. }
  359. // Loop through cells
  360. $row = $rowMin-1;
  361. while($row++ < $rowMax) {
  362. // <thead> ?
  363. if ($row == $theadStart) {
  364. $html .= ' <thead>' . PHP_EOL;
  365. }
  366. // <tbody> ?
  367. if ($row == $tbodyStart) {
  368. $html .= ' <tbody>' . PHP_EOL;
  369. }
  370. // Write row if there are HTML table cells in it
  371. if ( !isset($this->_isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row]) ) {
  372. // Start a new rowData
  373. $rowData = array();
  374. // Loop through columns
  375. $column = $dimension[0][0] - 1;
  376. while($column++ < $dimension[1][0]) {
  377. // Cell exists?
  378. if ($sheet->cellExistsByColumnAndRow($column, $row)) {
  379. $rowData[$column] = PHPExcel_Cell::stringFromColumnIndex($column) . $row;
  380. } else {
  381. $rowData[$column] = '';
  382. }
  383. }
  384. $html .= $this->_generateRow($sheet, $rowData, $row - 1);
  385. }
  386. // </thead> ?
  387. if ($row == $theadEnd) {
  388. $html .= ' </thead>' . PHP_EOL;
  389. }
  390. }
  391. $html .= $this->_extendRowsForChartsAndImages($sheet, $row);
  392. // Close table body.
  393. $html .= ' </tbody>' . PHP_EOL;
  394. // Write table footer
  395. $html .= $this->_generateTableFooter();
  396. // Writing PDF?
  397. if ($this->_isPdf) {
  398. if (is_null($this->_sheetIndex) && $sheetId + 1 < $this->_phpExcel->getSheetCount()) {
  399. $html .= '<div style="page-break-before:always" />';
  400. }
  401. }
  402. // Next sheet
  403. ++$sheetId;
  404. }
  405. // Return
  406. return $html;
  407. }
  408. /**
  409. * Generate sheet tabs
  410. *
  411. * @return string
  412. * @throws PHPExcel_Writer_Exception
  413. */
  414. public function generateNavigation()
  415. {
  416. // PHPExcel object known?
  417. if (is_null($this->_phpExcel)) {
  418. throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
  419. }
  420. // Fetch sheets
  421. $sheets = array();
  422. if (is_null($this->_sheetIndex)) {
  423. $sheets = $this->_phpExcel->getAllSheets();
  424. } else {
  425. $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
  426. }
  427. // Construct HTML
  428. $html = '';
  429. // Only if there are more than 1 sheets
  430. if (count($sheets) > 1) {
  431. // Loop all sheets
  432. $sheetId = 0;
  433. $html .= '<ul class="navigation">' . PHP_EOL;
  434. foreach ($sheets as $sheet) {
  435. $html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL;
  436. ++$sheetId;
  437. }
  438. $html .= '</ul>' . PHP_EOL;
  439. }
  440. return $html;
  441. }
  442. private function _extendRowsForChartsAndImages(PHPExcel_Worksheet $pSheet, $row) {
  443. $rowMax = $row;
  444. $colMax = 'A';
  445. if ($this->_includeCharts) {
  446. foreach ($pSheet->getChartCollection() as $chart) {
  447. if ($chart instanceof PHPExcel_Chart) {
  448. $chartCoordinates = $chart->getTopLeftPosition();
  449. $chartTL = PHPExcel_Cell::coordinateFromString($chartCoordinates['cell']);
  450. $chartCol = PHPExcel_Cell::columnIndexFromString($chartTL[0]);
  451. if ($chartTL[1] > $rowMax) {
  452. $rowMax = $chartTL[1];
  453. if ($chartCol > PHPExcel_Cell::columnIndexFromString($colMax)) {
  454. $colMax = $chartTL[0];
  455. }
  456. }
  457. }
  458. }
  459. }
  460. foreach ($pSheet->getDrawingCollection() as $drawing) {
  461. if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
  462. $imageTL = PHPExcel_Cell::coordinateFromString($drawing->getCoordinates());
  463. $imageCol = PHPExcel_Cell::columnIndexFromString($imageTL[0]);
  464. if ($imageTL[1] > $rowMax) {
  465. $rowMax = $imageTL[1];
  466. if ($imageCol > PHPExcel_Cell::columnIndexFromString($colMax)) {
  467. $colMax = $imageTL[0];
  468. }
  469. }
  470. }
  471. }
  472. $html = '';
  473. $colMax++;
  474. while ($row < $rowMax) {
  475. $html .= '<tr>';
  476. for ($col = 'A'; $col != $colMax; ++$col) {
  477. $html .= '<td>';
  478. $html .= $this->_writeImageInCell($pSheet, $col.$row);
  479. if ($this->_includeCharts) {
  480. $html .= $this->_writeChartInCell($pSheet, $col.$row);
  481. }
  482. $html .= '</td>';
  483. }
  484. ++$row;
  485. $html .= '</tr>';
  486. }
  487. return $html;
  488. }
  489. /**
  490. * Generate image tag in cell
  491. *
  492. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  493. * @param string $coordinates Cell coordinates
  494. * @return string
  495. * @throws PHPExcel_Writer_Exception
  496. */
  497. private function _writeImageInCell(PHPExcel_Worksheet $pSheet, $coordinates) {
  498. // Construct HTML
  499. $html = '';
  500. // Write images
  501. foreach ($pSheet->getDrawingCollection() as $drawing) {
  502. if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
  503. if ($drawing->getCoordinates() == $coordinates) {
  504. $filename = $drawing->getPath();
  505. // Strip off eventual '.'
  506. if (substr($filename, 0, 1) == '.') {
  507. $filename = substr($filename, 1);
  508. }
  509. // Prepend images root
  510. $filename = $this->getImagesRoot() . $filename;
  511. // Strip off eventual '.'
  512. if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
  513. $filename = substr($filename, 1);
  514. }
  515. // Convert UTF8 data to PCDATA
  516. $filename = htmlspecialchars($filename);
  517. $html .= PHP_EOL;
  518. if ((!$this->_embedImages) || ($this->_isPdf)) {
  519. $imageData = $filename;
  520. } else {
  521. $imageDetails = getimagesize($filename);
  522. if ($fp = fopen($filename,"rb", 0)) {
  523. $picture = fread($fp,filesize($filename));
  524. fclose($fp);
  525. // base64 encode the binary data, then break it
  526. // into chunks according to RFC 2045 semantics
  527. $base64 = chunk_split(base64_encode($picture));
  528. $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
  529. } else {
  530. $imageData = $filename;
  531. }
  532. }
  533. $html .= '<div style="position: relative;">';
  534. $html .= '<img style="position: absolute; z-index: 1; left: ' .
  535. $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' .
  536. $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' .
  537. $imageData . '" border="0" />';
  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. // Create CSS - add !important to non-none border styles for merged cells
  837. $borderStyle = $this->_mapBorderStyle($pStyle->getBorderStyle());
  838. $css = $borderStyle . ' #' . $pStyle->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important');
  839. // Return
  840. return $css;
  841. }
  842. /**
  843. * Create CSS style (PHPExcel_Style_Fill)
  844. *
  845. * @param PHPExcel_Style_Fill $pStyle PHPExcel_Style_Fill
  846. * @return array
  847. */
  848. private function _createCSSStyleFill(PHPExcel_Style_Fill $pStyle) {
  849. // Construct HTML
  850. $css = array();
  851. // Create CSS
  852. $value = $pStyle->getFillType() == PHPExcel_Style_Fill::FILL_NONE ?
  853. 'white' : '#' . $pStyle->getStartColor()->getRGB();
  854. $css['background-color'] = $value;
  855. // Return
  856. return $css;
  857. }
  858. /**
  859. * Generate HTML footer
  860. */
  861. public function generateHTMLFooter() {
  862. // Construct HTML
  863. $html = '';
  864. $html .= ' </body>' . PHP_EOL;
  865. $html .= '</html>' . PHP_EOL;
  866. // Return
  867. return $html;
  868. }
  869. /**
  870. * Generate table header
  871. *
  872. * @param PHPExcel_Worksheet $pSheet The worksheet for the table we are writing
  873. * @return string
  874. * @throws PHPExcel_Writer_Exception
  875. */
  876. private function _generateTableHeader($pSheet) {
  877. $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
  878. // Construct HTML
  879. $html = '';
  880. $html .= $this->_setMargins($pSheet);
  881. if (!$this->_useInlineCss) {
  882. $gridlines = $pSheet->getShowGridlines() ? ' gridlines' : '';
  883. $html .= ' <table border="0" cellpadding="0" cellspacing="0" id="sheet' . $sheetIndex . '" class="sheet' . $sheetIndex . $gridlines . '">' . PHP_EOL;
  884. } else {
  885. $style = isset($this->_cssStyles['table']) ?
  886. $this->_assembleCSS($this->_cssStyles['table']) : '';
  887. if ($this->_isPdf && $pSheet->getShowGridlines()) {
  888. $html .= ' <table border="1" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="1" style="' . $style . '">' . PHP_EOL;
  889. } else {
  890. $html .= ' <table border="0" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="0" style="' . $style . '">' . PHP_EOL;
  891. }
  892. }
  893. // Write <col> elements
  894. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) - 1;
  895. $i = -1;
  896. while($i++ < $highestColumnIndex) {
  897. if (!$this->_isPdf) {
  898. if (!$this->_useInlineCss) {
  899. $html .= ' <col class="col' . $i . '">' . PHP_EOL;
  900. } else {
  901. $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ?
  902. $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';
  903. $html .= ' <col style="' . $style . '">' . PHP_EOL;
  904. }
  905. }
  906. }
  907. // Return
  908. return $html;
  909. }
  910. /**
  911. * Generate table footer
  912. *
  913. * @throws PHPExcel_Writer_Exception
  914. */
  915. private function _generateTableFooter() {
  916. // Construct HTML
  917. $html = '';
  918. $html .= ' </table>' . PHP_EOL;
  919. // Return
  920. return $html;
  921. }
  922. /**
  923. * Generate row
  924. *
  925. * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
  926. * @param array $pValues Array containing cells in a row
  927. * @param int $pRow Row number (0-based)
  928. * @return string
  929. * @throws PHPExcel_Writer_Exception
  930. */
  931. private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0) {
  932. if (is_array($pValues)) {
  933. // Construct HTML
  934. $html = '';
  935. // Sheet index
  936. $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
  937. // DomPDF and breaks
  938. if ($this->_isPdf && count($pSheet->getBreaks()) > 0) {
  939. $breaks = $pSheet->getBreaks();
  940. // check if a break is needed before this row
  941. if (isset($breaks['A' . $pRow])) {
  942. // close table: </table>
  943. $html .= $this->_generateTableFooter();
  944. // insert page break
  945. $html .= '<div style="page-break-before:always" />';
  946. // open table again: <table> + <col> etc.
  947. $html .= $this->_generateTableHeader($pSheet);
  948. }
  949. }
  950. // Write row start
  951. if (!$this->_useInlineCss) {
  952. $html .= ' <tr class="row' . $pRow . '">' . PHP_EOL;
  953. } else {
  954. $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
  955. ? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
  956. $html .= ' <tr style="' . $style . '">' . PHP_EOL;
  957. }
  958. // Write cells
  959. $colNum = 0;
  960. foreach ($pValues as $cellAddress) {
  961. $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : '';
  962. $coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
  963. if (!$this->_useInlineCss) {
  964. $cssClass = '';
  965. $cssClass = 'column' . $colNum;
  966. } else {
  967. $cssClass = array();
  968. if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
  969. $this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
  970. }
  971. }
  972. $colSpan = 1;
  973. $rowSpan = 1;
  974. // initialize
  975. $cellData = '&nbsp;';
  976. // PHPExcel_Cell
  977. if ($cell instanceof PHPExcel_Cell) {
  978. $cellData = '';
  979. if (is_null($cell->getParent())) {
  980. $cell->attach($pSheet);
  981. }
  982. // Value
  983. if ($cell->getValue() instanceof PHPExcel_RichText) {
  984. // Loop through rich text elements
  985. $elements = $cell->getValue()->getRichTextElements();
  986. foreach ($elements as $element) {
  987. // Rich text start?
  988. if ($element instanceof PHPExcel_RichText_Run) {
  989. $cellData .= '<span style="' . $this->_assembleCSS($this->_createCSSStyleFont($element->getFont())) . '">';
  990. if ($element->getFont()->getSuperScript()) {
  991. $cellData .= '<sup>';
  992. } else if ($element->getFont()->getSubScript()) {
  993. $cellData .= '<sub>';
  994. }
  995. }
  996. // Convert UTF8 data to PCDATA
  997. $cellText = $element->getText();
  998. $cellData .= htmlspecialchars($cellText);
  999. if ($element instanceof PHPExcel_RichText_Run) {
  1000. if ($element->getFont()->getSuperScript()) {
  1001. $cellData .= '</sup>';
  1002. } else if ($element->getFont()->getSubScript()) {
  1003. $cellData .= '</sub>';
  1004. }
  1005. $cellData .= '</span>';
  1006. }
  1007. }
  1008. } else {
  1009. if ($this->_preCalculateFormulas) {
  1010. $cellData = PHPExcel_Style_NumberFormat::toFormattedString(
  1011. $cell->getCalculatedValue(),
  1012. $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
  1013. array($this, 'formatColor')
  1014. );
  1015. } else {
  1016. $cellData = PHPExcel_Style_NumberFormat::ToFormattedString(
  1017. $cell->getValue(),
  1018. $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
  1019. array($this, 'formatColor')
  1020. );
  1021. }
  1022. $cellData = htmlspecialchars($cellData);
  1023. if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) {
  1024. $cellData = '<sup>'.$cellData.'</sup>';
  1025. } elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) {
  1026. $cellData = '<sub>'.$cellData.'</sub>';
  1027. }
  1028. }
  1029. // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
  1030. // Example: " Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
  1031. $cellData = preg_replace("/(?m)(?:^|\\G) /", '&nbsp;', $cellData);
  1032. // convert newline "\n" to '<br>'
  1033. $cellData = nl2br($cellData);
  1034. // Extend CSS class?
  1035. if (!$this->_useInlineCss) {
  1036. $cssClass .= ' style' . $cell->getXfIndex();
  1037. $cssClass .= ' ' . $cell->getDataType();
  1038. } else {
  1039. if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) {
  1040. $cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]);
  1041. }
  1042. // General horizontal alignment: Actual horizontal alignment depends on dataType
  1043. $sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() );
  1044. if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL
  1045. && isset($this->_cssStyles['.' . $cell->getDataType()]['text-align']))
  1046. {
  1047. $cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align'];
  1048. }
  1049. }
  1050. }
  1051. // Hyperlink?
  1052. if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
  1053. $cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip()) . '">' . $cellData . '</a>';
  1054. }
  1055. // Should the cell be written or is it swallowed by a rowspan or colspan?
  1056. $writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
  1057. && $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] );
  1058. // Colspan and Rowspan
  1059. $colspan = 1;
  1060. $rowspan = 1;
  1061. if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
  1062. $spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
  1063. $rowSpan = $spans['rowspan'];
  1064. $colSpan = $spans['colspan'];
  1065. // Also apply style from last cell in merge to fix borders -
  1066. // relies on !important for non-none border declarations in _createCSSStyleBorder
  1067. $endCellCoord = PHPExcel_Cell::stringFromColumnIndex($colNum + $colSpan - 1) . ($pRow + $rowSpan);
  1068. if (!$this->_useInlineCss) {
  1069. $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex();
  1070. }
  1071. }
  1072. // Write
  1073. if ($writeCell) {
  1074. // Column start
  1075. $html .= ' <td';
  1076. if (!$this->_useInlineCss) {
  1077. $html .= ' class="' . $cssClass . '"';
  1078. } else {
  1079. //** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
  1080. // We must explicitly write the width of the <td> element because TCPDF
  1081. // does not recognize e.g. <col style="width:42pt">
  1082. $width = 0;
  1083. $i = $colNum - 1;
  1084. $e = $colNum + $colSpan - 1;
  1085. while($i++ < $e) {
  1086. if (isset($this->_columnWidths[$sheetIndex][$i])) {
  1087. $width += $this->_columnWidths[$sheetIndex][$i];
  1088. }
  1089. }
  1090. $cssClass['width'] = $width . 'pt';
  1091. // We must also explicitly write the height of the <td> element because TCPDF
  1092. // does not recognize e.g. <tr style="height:50pt">
  1093. if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
  1094. $height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
  1095. $cssClass['height'] = $height;
  1096. }
  1097. //** end of redundant code **
  1098. $html .= ' style="' . $this->_assembleCSS($cssClass) . '"';
  1099. }
  1100. if ($colSpan > 1) {
  1101. $html .= ' colspan="' . $colSpan . '"';
  1102. }
  1103. if ($rowSpan > 1) {
  1104. $html .= ' rowspan="' . $rowSpan . '"';
  1105. }
  1106. $html .= '>';
  1107. // Image?
  1108. $html .= $this->_writeImageInCell($pSheet, $coordinate);
  1109. // Chart?
  1110. if ($this->_includeCharts) {
  1111. $html .= $this->_writeChartInCell($pSheet, $coordinate);
  1112. }
  1113. // Cell data
  1114. $html .= $cellData;
  1115. // Column end
  1116. $html .= '</td>' . PHP_EOL;
  1117. }
  1118. // Next column
  1119. ++$colNum;
  1120. }
  1121. // Write row end
  1122. $html .= ' </tr>' . PHP_EOL;
  1123. // Return
  1124. return $html;
  1125. } else {
  1126. throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
  1127. }
  1128. }
  1129. /**
  1130. * Takes array where of CSS properties / values and converts to CSS string
  1131. *
  1132. * @param array
  1133. * @return string
  1134. */
  1135. private function _assembleCSS($pValue = array())
  1136. {
  1137. $pairs = array();
  1138. foreach ($pValue as $property => $value) {
  1139. $pairs[] = $property . ':' . $value;
  1140. }
  1141. $string = implode('; ', $pairs);
  1142. return $string;
  1143. }
  1144. /**
  1145. * Get images root
  1146. *
  1147. * @return string
  1148. */
  1149. public function getImagesRoot() {
  1150. return $this->_imagesRoot;
  1151. }
  1152. /**
  1153. * Set images root
  1154. *
  1155. * @param string $pValue
  1156. * @return PHPExcel_Writer_HTML
  1157. */
  1158. public function setImagesRoot($pValue = '.') {
  1159. $this->_imagesRoot = $pValue;
  1160. return $this;
  1161. }
  1162. /**
  1163. * Get embed images
  1164. *
  1165. * @return boolean
  1166. */
  1167. public function getEmbedImages() {
  1168. return $this->_embedImages;
  1169. }
  1170. /**
  1171. * Set embed images
  1172. *
  1173. * @param boolean $pValue
  1174. * @return PHPExcel_Writer_HTML
  1175. */
  1176. public function setEmbedImages($pValue = '.') {
  1177. $this->_embedImages = $pValue;
  1178. return $this;
  1179. }
  1180. /**
  1181. * Get use inline CSS?
  1182. *
  1183. * @return boolean
  1184. */
  1185. public function getUseInlineCss() {
  1186. return $this->_useInlineCss;
  1187. }
  1188. /**
  1189. * Set use inline CSS?
  1190. *
  1191. * @param boolean $pValue
  1192. * @return PHPExcel_Writer_HTML
  1193. */
  1194. public function setUseInlineCss($pValue = false) {
  1195. $this->_useInlineCss = $pValue;
  1196. return $this;
  1197. }
  1198. /**
  1199. * Add color to formatted string as inline style
  1200. *
  1201. * @param string $pValue Plain formatted value without color
  1202. * @param string $pFormat Format code
  1203. * @return string
  1204. */
  1205. public function formatColor($pValue, $pFormat)
  1206. {
  1207. // Color information, e.g. [Red] is always at the beginning
  1208. $color = null; // initialize
  1209. $matches = array();
  1210. $color_regex = '/^\\[[a-zA-Z]+\\]/';
  1211. if (preg_match($color_regex, $pFormat, $matches)) {
  1212. $color = str_replace('[', '', $matches[0]);
  1213. $color = str_replace(']', '', $color);
  1214. $color = strtolower($color);
  1215. }
  1216. // convert to PCDATA
  1217. $value = htmlspecialchars($pValue);
  1218. // color span tag
  1219. if ($color !== null) {
  1220. $value = '<span style="color:' . $color . '">' . $value . '</span>';
  1221. }
  1222. return $value;
  1223. }
  1224. /**
  1225. * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
  1226. */
  1227. private function _calculateSpans()
  1228. {
  1229. // Identify all cells that should be omitted in HTML due to cell merge.
  1230. // In HTML only the upper-left cell should be written and it should have
  1231. // appropriate rowspan / colspan attribute
  1232. $sheetIndexes = $this->_sheetIndex !== null ?
  1233. array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1);
  1234. foreach ($sheetIndexes as $sheetIndex) {
  1235. $sheet = $this->_phpExcel->getSheet($sheetIndex);
  1236. $candidateSpannedRow = array();
  1237. // loop through all Excel merged cells
  1238. foreach ($sheet->getMergeCells() as $cells) {
  1239. list($cells, ) = PHPExcel_Cell::splitRange($cells);
  1240. $first = $cells[0];
  1241. $last = $cells[1];
  1242. list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first);
  1243. $fc = PHPExcel_Cell::columnIndexFromString($fc) - 1;
  1244. list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last);
  1245. $lc = PHPExcel_Cell::columnIndexFromString($lc) - 1;
  1246. // loop through the individual cells in the individual merge
  1247. $r = $fr - 1;
  1248. while($r++ < $lr) {
  1249. // also, flag this row as a HTML row that is candidate to be omitted
  1250. $candidateSpannedRow[$r] = $r;
  1251. $c = $fc - 1;
  1252. while($c++ < $lc) {
  1253. if ( !($c == $fc && $r == $fr) ) {
  1254. // not the upper-left cell (should not be written in HTML)
  1255. $this->_isSpannedCell[$sheetIndex][$r][$c] = array(
  1256. 'baseCell' => array($fr, $fc),
  1257. );
  1258. } else {
  1259. // upper-left is the base cell that should hold the colspan/rowspan attribute
  1260. $this->_isBaseCell[$sheetIndex][$r][$c] = array(
  1261. 'xlrowspan' => $lr - $fr + 1, // Excel rowspan
  1262. 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
  1263. 'xlcolspan' => $lc - $fc + 1, // Excel colspan
  1264. 'colspan' => $lc - $fc + 1, // HTML colspan, value may change
  1265. );
  1266. }
  1267. }
  1268. }
  1269. }
  1270. // Identify which rows should be omitted in HTML. These are the rows where all the cells
  1271. // participate in a merge and the where base cells are somewhere above.
  1272. $countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
  1273. foreach ($candidateSpannedRow as $rowIndex) {
  1274. if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) {
  1275. if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
  1276. $this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
  1277. };
  1278. }
  1279. }
  1280. // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
  1281. if ( isset($this->_isSpannedRow[$sheetIndex]) ) {
  1282. foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) {
  1283. $adjustedBaseCells = array();
  1284. $c = -1;
  1285. $e = $countColumns - 1;
  1286. while($c++ < $e) {
  1287. $baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
  1288. if ( !in_array($baseCell, $adjustedBaseCells) ) {
  1289. // subtract rowspan by 1
  1290. --$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
  1291. $adjustedBaseCells[] = $baseCell;
  1292. }
  1293. }
  1294. }
  1295. }
  1296. // TODO: Same for columns
  1297. }
  1298. // We have calculated the spans
  1299. $this->_spansAreCalculated = true;
  1300. }
  1301. private function _setMargins(PHPExcel_Worksheet $pSheet) {
  1302. $htmlPage = '@page { ';
  1303. $htmlBody = 'body { ';
  1304. $left = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()) . 'in; ';
  1305. $htmlPage .= 'left-margin: ' . $left;
  1306. $htmlBody .= 'left-margin: ' . $left;
  1307. $right = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; ';
  1308. $htmlPage .= 'right-margin: ' . $right;
  1309. $htmlBody .= 'right-margin: ' . $right;
  1310. $top = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; ';
  1311. $htmlPage .= 'top-margin: ' . $top;
  1312. $htmlBody .= 'top-margin: ' . $top;
  1313. $bottom = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; ';
  1314. $htmlPage .= 'bottom-margin: ' . $bottom;
  1315. $htmlBody .= 'bottom-margin: ' . $bottom;
  1316. $htmlPage .= "}\n";
  1317. $htmlBody .= "}\n";
  1318. return "<style>\n" . $htmlPage . $htmlBody . "</style>\n";
  1319. }
  1320. }