483576ad2cf7396401205503d288ac3167bf1d5c.svn-base 46 KB

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