HTML.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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. }