HTML.php 59 KB

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