No Description

HTML.php 46KB

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