人人商城

HTML.php 44KB

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