PHPExcel_Writer_HTML::_mapHAlign()   B
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 9
c 0
b 0
f 0
nc 7
nop 1
dl 0
loc 11
rs 8.2222
1
<?php
2
/**
3
 * PHPExcel
4
 *
5
 * Copyright (c) 2006 - 2012 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
23
 * @copyright  Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
24
 * @license	http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
25
 * @version	1.7.7, 2012-05-19
26
 */
27
28
29
/**
30
 * PHPExcel_Writer_HTML
31
 *
32
 * @category   PHPExcel
33
 * @package	PHPExcel_Writer
34
 * @copyright  Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
35
 */
36
class PHPExcel_Writer_HTML implements PHPExcel_Writer_IWriter {
37
	/**
38
	 * PHPExcel object
39
	 *
40
	 * @var PHPExcel
41
	 */
42
	protected $_phpExcel;
43
44
	/**
45
	 * Sheet index to write
46
	 *
47
	 * @var int
48
	 */
49
	private $_sheetIndex	= 0;
50
51
	/**
52
	 * Pre-calculate formulas
53
	 *
54
	 * @var boolean
55
	 */
56
	private $_preCalculateFormulas = true;
57
58
	/**
59
	 * Images root
60
	 *
61
	 * @var string
62
	 */
63
	private $_imagesRoot	= '.';
64
65
	/**
66
	 * Use inline CSS?
67
	 *
68
	 * @var boolean
69
	 */
70
	private $_useInlineCss = false;
71
72
	/**
73
	 * Array of CSS styles
74
	 *
75
	 * @var array
76
	 */
77
	private $_cssStyles = null;
78
79
	/**
80
	 * Array of column widths in points
81
	 *
82
	 * @var array
83
	 */
84
	private $_columnWidths = null;
85
86
	/**
87
	 * Default font
88
	 *
89
	 * @var PHPExcel_Style_Font
90
	 */
91
	private $_defaultFont;
92
93
	/**
94
	 * Flag whether spans have been calculated
95
	 *
96
	 * @var boolean
97
	 */
98
	private $_spansAreCalculated	= false;
99
100
	/**
101
	 * Excel cells that should not be written as HTML cells
102
	 *
103
	 * @var array
104
	 */
105
	private $_isSpannedCell	= array();
106
107
	/**
108
	 * Excel cells that are upper-left corner in a cell merge
109
	 *
110
	 * @var array
111
	 */
112
	private $_isBaseCell	= array();
113
114
	/**
115
	 * Excel rows that should not be written as HTML rows
116
	 *
117
	 * @var array
118
	 */
119
	private $_isSpannedRow	= array();
120
121
	/**
122
	 * Is the current writer creating PDF?
123
	 *
124
	 * @var boolean
125
	 */
126
	protected $_isPdf = false;
127
128
	/**
129
	 * Generate the Navigation block
130
	 *
131
	 * @var boolean
132
	 */
133
	private $_generateSheetNavigationBlock = true;
134
135
	/**
136
	 * Create a new PHPExcel_Writer_HTML
137
	 *
138
	 * @param	PHPExcel	$phpExcel	PHPExcel object
139
	 */
140
	public function __construct(PHPExcel $phpExcel) {
141
		$this->_phpExcel = $phpExcel;
142
		$this->_defaultFont = $this->_phpExcel->getDefaultStyle()->getFont();
143
	}
144
145
	/**
146
	 * Save PHPExcel to file
147
	 *
148
	 * @param	string		$pFilename
149
	 * @throws	Exception
150
	 */
151
	public function save($pFilename = null) {
152
		// garbage collect
153
		$this->_phpExcel->garbageCollect();
154
155
		$saveDebugLog = PHPExcel_Calculation::getInstance()->writeDebugLog;
156
		PHPExcel_Calculation::getInstance()->writeDebugLog = false;
157
		$saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
158
		PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);
159
160
		// Build CSS
161
		$this->buildCSS(!$this->_useInlineCss);
162
163
		// Open file
164
		$fileHandle = fopen($pFilename, 'wb+');
165
		if ($fileHandle === false) {
166
			throw new Exception("Could not open file $pFilename for writing.");
167
		}
168
169
		// Write headers
170
		fwrite($fileHandle, $this->generateHTMLHeader(!$this->_useInlineCss));
171
172
		// Write navigation (tabs)
173
		if ((!$this->_isPdf) && ($this->_generateSheetNavigationBlock)) {
174
			fwrite($fileHandle, $this->generateNavigation());
175
		}
176
177
		// Write data
178
		fwrite($fileHandle, $this->generateSheetData());
179
180
		// Write footer
181
		fwrite($fileHandle, $this->generateHTMLFooter());
182
183
		// Close file
184
		fclose($fileHandle);
185
186
		PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
187
		PHPExcel_Calculation::getInstance()->writeDebugLog = $saveDebugLog;
188
	}
189
190
	/**
191
	 * Map VAlign
192
	 *
193
	 * @param	string		$vAlign		Vertical alignment
194
	 * @return string
195
	 */
196
	private function _mapVAlign($vAlign) {
197
		switch ($vAlign) {
198
			case PHPExcel_Style_Alignment::VERTICAL_BOTTOM:		return 'bottom';
199
			case PHPExcel_Style_Alignment::VERTICAL_TOP:		return 'top';
200
			case PHPExcel_Style_Alignment::VERTICAL_CENTER:
201
			case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY:	return 'middle';
202
			default: return 'baseline';
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
203
		}
204
	}
205
206
	/**
207
	 * Map HAlign
208
	 *
209
	 * @param	string		$hAlign		Horizontal alignment
210
	 * @return string|false
211
	 */
212
	private function _mapHAlign($hAlign) {
213
		switch ($hAlign) {
214
			case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL:				return false;
215
			case PHPExcel_Style_Alignment::HORIZONTAL_LEFT:					return 'left';
216
			case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT:				return 'right';
217
			case PHPExcel_Style_Alignment::HORIZONTAL_CENTER:
218
			case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS:	return 'center';
219
			case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY:				return 'justify';
220
			default: return false;
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
221
		}
222
	}
223
224
	/**
225
	 * Map border style
226
	 *
227
	 * @param	int		$borderStyle		Sheet index
228
	 * @return	string
229
	 */
230 View Code Duplication
	private function _mapBorderStyle($borderStyle) {
231
		switch ($borderStyle) {
232
			case PHPExcel_Style_Border::BORDER_NONE:				return '1px hidden';
233
			case PHPExcel_Style_Border::BORDER_DASHDOT:				return '1px dashed';
234
			case PHPExcel_Style_Border::BORDER_DASHDOTDOT:			return '1px dotted';
235
			case PHPExcel_Style_Border::BORDER_DASHED:				return '1px dashed';
236
			case PHPExcel_Style_Border::BORDER_DOTTED:				return '1px dotted';
237
			case PHPExcel_Style_Border::BORDER_DOUBLE:				return '3px double';
238
			case PHPExcel_Style_Border::BORDER_HAIR:				return '1px solid';
239
			case PHPExcel_Style_Border::BORDER_MEDIUM:				return '2px solid';
240
			case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT:		return '2px dashed';
241
			case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT:	return '2px dotted';
242
			case PHPExcel_Style_Border::BORDER_MEDIUMDASHED:		return '2px dashed';
243
			case PHPExcel_Style_Border::BORDER_SLANTDASHDOT:		return '2px dashed';
244
			case PHPExcel_Style_Border::BORDER_THICK:				return '3px solid';
245
			case PHPExcel_Style_Border::BORDER_THIN:				return '1px solid';
246
			default: return '1px solid'; // map others to thin
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
247
		}
248
	}
249
250
	/**
251
	 * Get sheet index
252
	 *
253
	 * @return int
254
	 */
255
	public function getSheetIndex() {
256
		return $this->_sheetIndex;
257
	}
258
259
	/**
260
	 * Set sheet index
261
	 *
262
	 * @param	int		$pValue		Sheet index
263
	 * @return PHPExcel_Writer_HTML
264
	 */
265
	public function setSheetIndex($pValue = 0) {
266
		$this->_sheetIndex = $pValue;
267
		return $this;
268
	}
269
270
	/**
271
	 * Get sheet index
272
	 *
273
	 * @return boolean
274
	 */
275
	public function getGenerateSheetNavigationBlock() {
276
		return $this->_generateSheetNavigationBlock;
277
	}
278
279
	/**
280
	 * Set sheet index
281
	 *
282
	 * @param	boolean		$pValue		Flag indicating whether the sheet navigation block should be generated or not
283
	 * @return PHPExcel_Writer_HTML
284
	 */
285
	public function setGenerateSheetNavigationBlock($pValue = true) {
286
		$this->_generateSheetNavigationBlock = (bool) $pValue;
287
		return $this;
288
	}
289
290
	/**
291
	 * Write all sheets (resets sheetIndex to NULL)
292
	 */
293
	public function writeAllSheets() {
294
		$this->_sheetIndex = null;
295
		return $this;
296
	}
297
298
	/**
299
	 * Generate HTML header
300
	 *
301
	 * @param	boolean		$pIncludeStyles		Include styles?
302
	 * @return	string
303
	 * @throws Exception
304
	 */
305
	public function generateHTMLHeader($pIncludeStyles = false) {
306
		// PHPExcel object known?
307
		if (is_null($this->_phpExcel)) {
308
			throw new Exception('Internal PHPExcel object not set to an instance of an object.');
309
		}
310
311
		// Construct HTML
312
		$properties = $this->_phpExcel->getProperties();
313
		$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' . PHP_EOL;
314
		$html .= '<!-- Generated by PHPExcel - http://www.phpexcel.net -->' . PHP_EOL;
315
		$html .= '<html>' . PHP_EOL;
316
		$html .= '  <head>' . PHP_EOL;
317
		$html .= '	  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . PHP_EOL;
318
		if ($properties->getTitle() > '')
319
			$html .= '	  <title>' . htmlspecialchars($properties->getTitle()) . '</title>' . PHP_EOL;
320
321
		if ($properties->getCreator() > '')
322
			$html .= '	  <meta name="author" content="' . htmlspecialchars($properties->getCreator()) . '" />' . PHP_EOL;
323
		if ($properties->getTitle() > '')
324
			$html .= '	  <meta name="title" content="' . htmlspecialchars($properties->getTitle()) . '" />' . PHP_EOL;
325 View Code Duplication
		if ($properties->getDescription() > '')
326
			$html .= '	  <meta name="description" content="' . htmlspecialchars($properties->getDescription()) . '" />' . PHP_EOL;
327
		if ($properties->getSubject() > '')
328
			$html .= '	  <meta name="subject" content="' . htmlspecialchars($properties->getSubject()) . '" />' . PHP_EOL;
329
		if ($properties->getKeywords() > '')
330
			$html .= '	  <meta name="keywords" content="' . htmlspecialchars($properties->getKeywords()) . '" />' . PHP_EOL;
331
		if ($properties->getCategory() > '')
332
			$html .= '	  <meta name="category" content="' . htmlspecialchars($properties->getCategory()) . '" />' . PHP_EOL;
333 View Code Duplication
		if ($properties->getCompany() > '')
334
			$html .= '	  <meta name="company" content="' . htmlspecialchars($properties->getCompany()) . '" />' . PHP_EOL;
335 View Code Duplication
		if ($properties->getManager() > '')
336
			$html .= '	  <meta name="manager" content="' . htmlspecialchars($properties->getManager()) . '" />' . PHP_EOL;
337
338
		if ($pIncludeStyles) {
339
			$html .= $this->generateStyles(true);
340
		}
341
342
		$html .= '  </head>' . PHP_EOL;
343
		$html .= '' . PHP_EOL;
344
		$html .= '  <body>' . PHP_EOL;
345
346
		// Return
347
		return $html;
348
	}
349
350
	/**
351
	 * Generate sheet data
352
	 *
353
	 * @return	string
354
	 * @throws Exception
355
	 */
356
	public function generateSheetData() {
357
		// PHPExcel object known?
358
		if (is_null($this->_phpExcel)) {
359
			throw new Exception('Internal PHPExcel object not set to an instance of an object.');
360
		}
361
362
		// Ensure that Spans have been calculated?
363
		if (!$this->_spansAreCalculated) {
364
			$this->_calculateSpans();
365
		}
366
367
		// Fetch sheets
368
		$sheets = array();
369 View Code Duplication
		if (is_null($this->_sheetIndex)) {
370
			$sheets = $this->_phpExcel->getAllSheets();
371
		} else {
372
			$sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
373
		}
374
375
		// Construct HTML
376
		$html = '';
377
378
		// Loop all sheets
379
		$sheetId = 0;
380
		foreach ($sheets as $sheet) {
381
			// Write table header
382
			$html .= $this->_generateTableHeader($sheet);
383
384
			// Get worksheet dimension
385
			$dimension = explode(':', $sheet->calculateWorksheetDimension());
386
			$dimension[0] = PHPExcel_Cell::coordinateFromString($dimension[0]);
387
			$dimension[0][0] = PHPExcel_Cell::columnIndexFromString($dimension[0][0]) - 1;
388
			$dimension[1] = PHPExcel_Cell::coordinateFromString($dimension[1]);
389
			$dimension[1][0] = PHPExcel_Cell::columnIndexFromString($dimension[1][0]) - 1;
390
391
			// row min,max
392
			$rowMin = $dimension[0][1];
393
			$rowMax = $dimension[1][1];
394
395
			// calculate start of <tbody>, <thead>
396
			$tbodyStart = $rowMin;
397
			$tbodyEnd   = $rowMax;
398
			$theadStart = $theadEnd   = 0; // default: no <thead>	no </thead>
399
			if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
400
				$rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();
401
402
				// we can only support repeating rows that start at top row
403
				if ($rowsToRepeatAtTop[0] == 1) {
404
					$theadStart = $rowsToRepeatAtTop[0];
405
					$theadEnd   = $rowsToRepeatAtTop[1];
406
					$tbodyStart = $rowsToRepeatAtTop[1] + 1;
407
				}
408
			}
409
410
			// Loop through cells
411
			$row = $rowMin-1;
412
			while($row++ < $rowMax) {
413
				// <thead> ?
414
				if ($row == $theadStart) {
415
					$html .= '		<thead>' . PHP_EOL;
416
				}
417
418
				// <tbody> ?
419
				if ($row == $tbodyStart) {
420
					$html .= '		<tbody>' . PHP_EOL;
421
				}
422
423
				// Write row if there are HTML table cells in it
424
				if ( !isset($this->_isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row]) ) {
425
					// Start a new rowData
426
					$rowData = array();
427
					// Loop through columns
428
					$column = $dimension[0][0] - 1;
429
					while($column++ < $dimension[1][0]) {
430
						// Cell exists?
431
						if ($sheet->cellExistsByColumnAndRow($column, $row)) {
432
							$rowData[$column] = $sheet->getCellByColumnAndRow($column, $row);
433
						} else {
434
							$rowData[$column] = '';
435
						}
436
					}
437
					$html .= $this->_generateRow($sheet, $rowData, $row - 1);
438
				}
439
440
				// </thead> ?
441
				if ($row == $theadEnd) {
442
					$html .= '		</thead>' . PHP_EOL;
443
				}
444
445
				// </tbody> ?
446
				if ($row == $tbodyEnd) {
447
					$html .= '		</tbody>' . PHP_EOL;
448
				}
449
			}
450
451
			// Write table footer
452
			$html .= $this->_generateTableFooter();
453
454
			// Writing PDF?
455
			if ($this->_isPdf) {
456
				if (is_null($this->_sheetIndex) && $sheetId + 1 < $this->_phpExcel->getSheetCount()) {
457
					$html .= '<div style="page-break-before:always" />';
458
				}
459
			}
460
461
			// Next sheet
462
			++$sheetId;
463
		}
464
465
		// Return
466
		return $html;
467
	}
468
469
	/**
470
	 * Generate sheet tabs
471
	 *
472
	 * @return	string
473
	 * @throws Exception
474
	 */
475
	public function generateNavigation()
476
	{
477
		// PHPExcel object known?
478
		if (is_null($this->_phpExcel)) {
479
			throw new Exception('Internal PHPExcel object not set to an instance of an object.');
480
		}
481
482
		// Fetch sheets
483
		$sheets = array();
484 View Code Duplication
		if (is_null($this->_sheetIndex)) {
485
			$sheets = $this->_phpExcel->getAllSheets();
486
		} else {
487
			$sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
488
		}
489
490
		// Construct HTML
491
		$html = '';
492
493
		// Only if there are more than 1 sheets
494
		if (count($sheets) > 1) {
495
			// Loop all sheets
496
			$sheetId = 0;
497
498
			$html .= '<ul class="navigation">' . PHP_EOL;
499
500
			foreach ($sheets as $sheet) {
501
				$html .= '  <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL;
502
				++$sheetId;
503
			}
504
505
			$html .= '</ul>' . PHP_EOL;
506
		}
507
508
		return $html;
509
	}
510
511
	/**
512
	 * Generate image tag in cell
513
	 *
514
	 * @param	PHPExcel_Worksheet	$pSheet			PHPExcel_Worksheet
515
	 * @param	string				$coordinates	Cell coordinates
516
	 * @return	string
517
	 * @throws	Exception
518
	 */
519
	private function _writeImageTagInCell(PHPExcel_Worksheet $pSheet, $coordinates) {
520
		// Construct HTML
521
		$html = '';
522
523
		// Write images
524
		foreach ($pSheet->getDrawingCollection() as $drawing) {
525
			if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
526
				if ($drawing->getCoordinates() == $coordinates) {
527
					$filename = $drawing->getPath();
528
529
					// Strip off eventual '.'
530
					if (substr($filename, 0, 1) == '.') {
531
						$filename = substr($filename, 1);
532
					}
533
534
					// Prepend images root
535
					$filename = $this->getImagesRoot() . $filename;
536
537
					// Strip off eventual '.'
538
					if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
539
						$filename = substr($filename, 1);
540
					}
541
542
					// Convert UTF8 data to PCDATA
543
					$filename = htmlspecialchars($filename);
544
545
					$html .= PHP_EOL;
546
					$html .= '		<img style="position: relative; left: ' . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' . $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . $filename . '" border="0" width="' . $drawing->getWidth() . '" height="' . $drawing->getHeight() . '" />' . PHP_EOL;
547
				}
548
			}
549
		}
550
551
		// Return
552
		return $html;
553
	}
554
555
	/**
556
	 * Generate CSS styles
557
	 *
558
	 * @param	boolean	$generateSurroundingHTML	Generate surrounding HTML tags? (<style> and </style>)
559
	 * @return	string
560
	 * @throws	Exception
561
	 */
562
	public function generateStyles($generateSurroundingHTML = true) {
563
		// PHPExcel object known?
564
		if (is_null($this->_phpExcel)) {
565
			throw new Exception('Internal PHPExcel object not set to an instance of an object.');
566
		}
567
568
		// Build CSS
569
		$css = $this->buildCSS($generateSurroundingHTML);
570
571
		// Construct HTML
572
		$html = '';
573
574
		// Start styles
575
		if ($generateSurroundingHTML) {
576
			$html .= '	<style type="text/css">' . PHP_EOL;
577
			$html .= '	  html { ' . $this->_assembleCSS($css['html']) . ' }' . PHP_EOL;
578
		}
579
580
		// Write all other styles
581
		foreach ($css as $styleName => $styleDefinition) {
582
			if ($styleName != 'html') {
583
				$html .= '	  ' . $styleName . ' { ' . $this->_assembleCSS($styleDefinition) . ' }' . PHP_EOL;
584
			}
585
		}
586
587
		// End styles
588
		if ($generateSurroundingHTML) {
589
			$html .= '	</style>' . PHP_EOL;
590
		}
591
592
		// Return
593
		return $html;
594
	}
595
596
	/**
597
	 * Build CSS styles
598
	 *
599
	 * @param	boolean	$generateSurroundingHTML	Generate surrounding HTML style? (html { })
600
	 * @return	array
601
	 * @throws	Exception
602
	 */
603
	public function buildCSS($generateSurroundingHTML = true) {
604
		// PHPExcel object known?
605
		if (is_null($this->_phpExcel)) {
606
			throw new Exception('Internal PHPExcel object not set to an instance of an object.');
607
		}
608
609
		// Cached?
610
		if (!is_null($this->_cssStyles)) {
611
			return $this->_cssStyles;
612
		}
613
614
		// Ensure that spans have been calculated
615
		if (!$this->_spansAreCalculated) {
616
			$this->_calculateSpans();
617
		}
618
619
		// Construct CSS
620
		$css = array();
621
622
		// Start styles
623
		if ($generateSurroundingHTML) {
624
			// html { }
625
			$css['html']['font-family']	  = 'Calibri, Arial, Helvetica, sans-serif';
626
			$css['html']['font-size']		= '11pt';
627
			$css['html']['background-color'] = 'white';
628
		}
629
630
631
		// table { }
632
		$css['table']['border-collapse']  = 'collapse';
633
		$css['table']['page-break-after'] = 'always';
634
635
		// .gridlines td { }
636
		$css['.gridlines td']['border'] = '1px dotted black';
637
638
		// .b {}
639
		$css['.b']['text-align'] = 'center'; // BOOL
640
641
		// .e {}
642
		$css['.e']['text-align'] = 'center'; // ERROR
643
644
		// .f {}
645
		$css['.f']['text-align'] = 'right'; // FORMULA
646
647
		// .inlineStr {}
648
		$css['.inlineStr']['text-align'] = 'left'; // INLINE
649
650
		// .n {}
651
		$css['.n']['text-align'] = 'right'; // NUMERIC
652
653
		// .s {}
654
		$css['.s']['text-align'] = 'left'; // STRING
655
656
		// Calculate cell style hashes
657
		foreach ($this->_phpExcel->getCellXfCollection() as $index => $style) {
658
			$css['td.style' . $index] = $this->_createCSSStyle( $style );
659
		}
660
661
		// Fetch sheets
662
		$sheets = array();
663 View Code Duplication
		if (is_null($this->_sheetIndex)) {
664
			$sheets = $this->_phpExcel->getAllSheets();
665
		} else {
666
			$sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);
667
		}
668
669
		// Build styles per sheet
670
		foreach ($sheets as $sheet) {
671
			// Calculate hash code
672
			$sheetIndex = $sheet->getParent()->getIndex($sheet);
673
674
			// Build styles
675
			// Calculate column widths
676
			$sheet->calculateColumnWidths();
677
678
			// col elements, initialize
679
			$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) - 1;
680
			$column = -1;
681
			while($column++ < $highestColumnIndex) {
682
				$this->_columnWidths[$sheetIndex][$column] = 42; // approximation
683
				$css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt';
684
			}
685
686
			// col elements, loop through columnDimensions and set width
687
			foreach ($sheet->getColumnDimensions() as $columnDimension) {
688
				if (($width = PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth(), $this->_defaultFont)) >= 0) {
689
					$width = PHPExcel_Shared_Drawing::pixelsToPoints($width);
690
					$column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1;
691
					$this->_columnWidths[$sheetIndex][$column] = $width;
692
					$css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt';
693
694 View Code Duplication
					if ($columnDimension->getVisible() === false) {
695
						$css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse';
696
						$css['table.sheet' . $sheetIndex . ' col.col' . $column]['*display'] = 'none'; // target IE6+7
697
					}
698
				}
699
			}
700
701
			// Default row height
702
			$rowDimension = $sheet->getDefaultRowDimension();
703
704
			// table.sheetN tr { }
705
			$css['table.sheet' . $sheetIndex . ' tr'] = array();
706
707 View Code Duplication
			if ($rowDimension->getRowHeight() == -1) {
708
				$pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont());
709
			} else {
710
				$pt_height = $rowDimension->getRowHeight();
711
			}
712
			$css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt';
713
			if ($rowDimension->getVisible() === false) {
714
				$css['table.sheet' . $sheetIndex . ' tr']['display']	= 'none';
715
				$css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden';
716
			}
717
718
			// Calculate row heights
719
			foreach ($sheet->getRowDimensions() as $rowDimension) {
720
				$row = $rowDimension->getRowIndex() - 1;
721
722
				// table.sheetN tr.rowYYYYYY { }
723
				$css['table.sheet' . $sheetIndex . ' tr.row' . $row] = array();
724
725 View Code Duplication
				if ($rowDimension->getRowHeight() == -1) {
726
					$pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont());
727
				} else {
728
					$pt_height = $rowDimension->getRowHeight();
729
				}
730
				$css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt';
731 View Code Duplication
				if ($rowDimension->getVisible() === false) {
732
					$css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none';
733
					$css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden';
734
				}
735
			}
736
		}
737
738
		// Cache
739
		if (is_null($this->_cssStyles)) {
740
			$this->_cssStyles = $css;
741
		}
742
743
		// Return
744
		return $css;
745
	}
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
757
		// Create CSS
758
		$css = array_merge(
759
			$this->_createCSSStyleAlignment($pStyle->getAlignment())
760
			, $this->_createCSSStyleBorders($pStyle->getBorders())
761
			, $this->_createCSSStyleFont($pStyle->getFont())
762
			, $this->_createCSSStyleFill($pStyle->getFill())
763
		);
764
765
		// Return
766
		return $css;
767
	}
768
769
	/**
770
	 * Create CSS style (PHPExcel_Style_Alignment)
771
	 *
772
	 * @param	PHPExcel_Style_Alignment		$pStyle			PHPExcel_Style_Alignment
773
	 * @return	array
774
	 */
775
	private function _createCSSStyleAlignment(PHPExcel_Style_Alignment $pStyle) {
776
		// Construct CSS
777
		$css = array();
778
779
		// Create CSS
780
		$css['vertical-align'] = $this->_mapVAlign($pStyle->getVertical());
781
		if ($textAlign = $this->_mapHAlign($pStyle->getHorizontal())) {
782
			$css['text-align'] = $textAlign;
783
		}
784
785
		// Return
786
		return $css;
787
	}
788
789
	/**
790
	 * Create CSS style (PHPExcel_Style_Font)
791
	 *
792
	 * @param	PHPExcel_Style_Font		$pStyle			PHPExcel_Style_Font
793
	 * @return	array
794
	 */
795
	private function _createCSSStyleFont(PHPExcel_Style_Font $pStyle) {
796
		// Construct CSS
797
		$css = array();
798
799
		// Create CSS
800
		if ($pStyle->getBold()) {
801
			$css['font-weight'] = 'bold';
802
		}
803
		if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
804
			$css['text-decoration'] = 'underline line-through';
805
		} else if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE) {
806
			$css['text-decoration'] = 'underline';
807
		} else if ($pStyle->getStrikethrough()) {
808
			$css['text-decoration'] = 'line-through';
809
		}
810
		if ($pStyle->getItalic()) {
811
			$css['font-style'] = 'italic';
812
		}
813
814
		$css['color']		= '#' . $pStyle->getColor()->getRGB();
815
		$css['font-family']	= '\'' . $pStyle->getName() . '\'';
816
		$css['font-size']	= $pStyle->getSize() . 'pt';
817
818
		// Return
819
		return $css;
820
	}
821
822
	/**
823
	 * Create CSS style (PHPExcel_Style_Borders)
824
	 *
825
	 * @param	PHPExcel_Style_Borders		$pStyle			PHPExcel_Style_Borders
826
	 * @return	array
827
	 */
828
	private function _createCSSStyleBorders(PHPExcel_Style_Borders $pStyle) {
829
		// Construct CSS
830
		$css = array();
831
832
		// Create CSS
833
		$css['border-bottom']	= $this->_createCSSStyleBorder($pStyle->getBottom());
834
		$css['border-top']		= $this->_createCSSStyleBorder($pStyle->getTop());
835
		$css['border-left']		= $this->_createCSSStyleBorder($pStyle->getLeft());
836
		$css['border-right']	= $this->_createCSSStyleBorder($pStyle->getRight());
837
838
		// Return
839
		return $css;
840
	}
841
842
	/**
843
	 * Create CSS style (PHPExcel_Style_Border)
844
	 *
845
	 * @param	PHPExcel_Style_Border		$pStyle			PHPExcel_Style_Border
846
	 * @return	string
847
	 */
848
	private function _createCSSStyleBorder(PHPExcel_Style_Border $pStyle) {
849
		// Create CSS
850
		$css = $this->_mapBorderStyle($pStyle->getBorderStyle()) . ' #' . $pStyle->getColor()->getRGB();
851
852
		// Return
853
		return $css;
854
	}
855
856
	/**
857
	 * Create CSS style (PHPExcel_Style_Fill)
858
	 *
859
	 * @param	PHPExcel_Style_Fill		$pStyle			PHPExcel_Style_Fill
860
	 * @return	array
861
	 */
862
	private function _createCSSStyleFill(PHPExcel_Style_Fill $pStyle) {
863
		// Construct HTML
864
		$css = array();
865
866
		// Create CSS
867
		$value = $pStyle->getFillType() == PHPExcel_Style_Fill::FILL_NONE ?
868
			'white' : '#' . $pStyle->getStartColor()->getRGB();
869
		$css['background-color'] = $value;
870
871
		// Return
872
		return $css;
873
	}
874
875
	/**
876
	 * Generate HTML footer
877
	 */
878
	public function generateHTMLFooter() {
879
		// Construct HTML
880
		$html = '';
881
		$html .= '  </body>' . PHP_EOL;
882
		$html .= '</html>' . PHP_EOL;
883
884
		// Return
885
		return $html;
886
	}
887
888
	/**
889
	 * Generate table header
890
	 *
891
	 * @param	PHPExcel_Worksheet	$pSheet		The worksheet for the table we are writing
892
	 * @return	string
893
	 * @throws	Exception
894
	 */
895
	private function _generateTableHeader($pSheet) {
896
		$sheetIndex = $pSheet->getParent()->getIndex($pSheet);
897
898
		// Construct HTML
899
		$html = '';
900
901
		if (!$this->_useInlineCss) {
902
			$gridlines = $pSheet->getShowGridLines() ? ' gridlines' : '';
903
			$html .= '	<table border="0" cellpadding="0" cellspacing="0" id="sheet' . $sheetIndex . '" class="sheet' . $sheetIndex . $gridlines . '">' . PHP_EOL;
904 View Code Duplication
		} else {
905
			$style = isset($this->_cssStyles['table']) ?
906
				$this->_assembleCSS($this->_cssStyles['table']) : '';
907
908
			if ($this->_isPdf && $pSheet->getShowGridLines()) {
909
				$html .= '	<table border="1" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="4" style="' . $style . '">' . PHP_EOL;
910
			} else {
911
				$html .= '	<table border="0" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="4" style="' . $style . '">' . PHP_EOL;
912
			}
913
		}
914
915
		// Write <col> elements
916
		$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) - 1;
917
		$i = -1;
918
		while($i++ < $highestColumnIndex) {
919 View Code Duplication
			if (!$this->_useInlineCss) {
920
				$html .= '		<col class="col' . $i . '">' . PHP_EOL;
921
			} else {
922
				$style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ?
923
					$this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';
924
				$html .= '		<col style="' . $style . '">' . PHP_EOL;
925
			}
926
		}
927
928
		// Return
929
		return $html;
930
	}
931
932
	/**
933
	 * Generate table footer
934
	 *
935
	 * @throws	Exception
936
	 */
937
	private function _generateTableFooter() {
938
		// Construct HTML
939
		$html = '';
940
		$html .= '	</table>' . PHP_EOL;
941
942
		// Return
943
		return $html;
944
	}
945
946
	/**
947
	 * Generate row
948
	 *
949
	 * @param	PHPExcel_Worksheet	$pSheet			PHPExcel_Worksheet
950
	 * @param	array				$pValues		Array containing cells in a row
951
	 * @param	int					$pRow			Row number (0-based)
952
	 * @return	string
953
	 * @throws	Exception
954
	 */
955
	private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0) {
956
		if (is_array($pValues)) {
957
			// Construct HTML
958
			$html = '';
959
960
			// Sheet index
961
			$sheetIndex = $pSheet->getParent()->getIndex($pSheet);
962
963
			// DomPDF and breaks
964
			if ($this->_isPdf && count($pSheet->getBreaks()) > 0) {
965
				$breaks = $pSheet->getBreaks();
966
967
				// check if a break is needed before this row
968
				if (isset($breaks['A' . $pRow])) {
969
					// close table: </table>
970
					$html .= $this->_generateTableFooter();
971
972
					// insert page break
973
					$html .= '<div style="page-break-before:always" />';
974
975
					// open table again: <table> + <col> etc.
976
					$html .= $this->_generateTableHeader($pSheet);
977
				}
978
			}
979
980
			// Write row start
981 View Code Duplication
			if (!$this->_useInlineCss) {
982
				$html .= '		  <tr class="row' . $pRow . '">' . PHP_EOL;
983
			} else {
984
				$style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
985
					? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
986
987
				$html .= '		  <tr style="' . $style . '">' . PHP_EOL;
988
			}
989
990
			// Write cells
991
			$colNum = 0;
992
			foreach ($pValues as $cell) {
993
				$coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
994
995
				if (!$this->_useInlineCss) {
996
					$cssClass = '';
997
					$cssClass = 'column' . $colNum;
998
				} else {
999
					$cssClass = array();
1000
					if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
1001
						$this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
1002
					}
1003
				}
1004
				$colSpan = 1;
1005
				$rowSpan = 1;
1006
1007
				// initialize
1008
				$cellData = '';
1009
1010
				// PHPExcel_Cell
1011
				if ($cell instanceof PHPExcel_Cell) {
1012
					if (is_null($cell->getParent())) {
1013
						$cell->attach($pSheet);
1014
					}
1015
					// Value
1016
					if ($cell->getValue() instanceof PHPExcel_RichText) {
1017
						// Loop through rich text elements
1018
						$elements = $cell->getValue()->getRichTextElements();
1019
						foreach ($elements as $element) {
1020
							// Rich text start?
1021
							if ($element instanceof PHPExcel_RichText_Run) {
1022
								$cellData .= '<span style="' . $this->_assembleCSS($this->_createCSSStyleFont($element->getFont())) . '">';
1023
1024
								if ($element->getFont()->getSuperScript()) {
1025
									$cellData .= '<sup>';
1026
								} else if ($element->getFont()->getSubScript()) {
1027
									$cellData .= '<sub>';
1028
								}
1029
							}
1030
1031
							// Convert UTF8 data to PCDATA
1032
							$cellText = $element->getText();
1033
							$cellData .= htmlspecialchars($cellText);
1034
1035
							if ($element instanceof PHPExcel_RichText_Run) {
1036
								if ($element->getFont()->getSuperScript()) {
1037
									$cellData .= '</sup>';
1038
								} else if ($element->getFont()->getSubScript()) {
1039
									$cellData .= '</sub>';
1040
								}
1041
1042
								$cellData .= '</span>';
1043
							}
1044
						}
1045
					} else {
1046
						if ($this->_preCalculateFormulas) {
1047
							$cellData = PHPExcel_Style_NumberFormat::toFormattedString(
1048
								$cell->getCalculatedValue(),
1049
								$pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
1050
								array($this, 'formatColor')
1051
							);
1052
						} else {
1053
							$cellData = PHPExcel_Style_NumberFormat::ToFormattedString(
1054
								$cell->getValue(),
1055
								$pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
1056
								array($this, 'formatColor')
1057
							);
1058
						}
1059
						if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) {
1060
							$cellData = '<sup>'.$cellData.'</sup>';
1061
						} elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) {
1062
							$cellData = '<sub>'.$cellData.'</sub>';
1063
						}
1064
					}
1065
1066
					// Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
1067
					// Example: "  Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
1068
					$cellData = preg_replace("/(?m)(?:^|\\G) /", '&nbsp;', $cellData);
1069
1070
					// convert newline "\n" to '<br>'
1071
					$cellData = nl2br($cellData);
1072
1073
					// Extend CSS class?
1074
					if (!$this->_useInlineCss) {
1075
						$cssClass .= ' style' . $cell->getXfIndex();
1076
						$cssClass .= ' ' . $cell->getDataType();
1077
					} else {
1078
						if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) {
1079
							$cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]);
1080
						}
1081
1082
						// General horizontal alignment: Actual horizontal alignment depends on dataType
1083
						$sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() );
1084
						if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL
1085
							&& isset($this->_cssStyles['.' . $cell->getDataType()]['text-align']))
1086
						{
1087
							$cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align'];
1088
						}
1089
					}
1090
				}
1091
1092
				// Hyperlink?
1093
				if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
1094
					$cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip()) . '">' . $cellData . '</a>';
1095
				}
1096
1097
				// Should the cell be written or is it swallowed by a rowspan or colspan?
1098
				$writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
1099
							&& $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] );
1100
1101
				// Colspan and Rowspan
1102
				$colspan = 1;
1103
				$rowspan = 1;
1104
				if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
1105
					$spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
1106
					$rowSpan = $spans['rowspan'];
1107
					$colSpan = $spans['colspan'];
1108
				}
1109
1110
				// Write
1111
				if ($writeCell) {
1112
					// Column start
1113
					$html .= '			<td';
1114
						if (!$this->_useInlineCss) {
1115
							$html .= ' class="' . $cssClass . '"';
1116
						} else {
1117
							//** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
1118
							// We must explicitly write the width of the <td> element because TCPDF
1119
							// does not recognize e.g. <col style="width:42pt">
1120
							$width = 0;
1121
							$i = $colNum - 1;
1122
							$e = $colNum + $colSpan - 1;
1123
							while($i++ < $e) {
1124
								if (isset($this->_columnWidths[$sheetIndex][$i])) {
1125
									$width += $this->_columnWidths[$sheetIndex][$i];
1126
								}
1127
							}
1128
							$cssClass['width'] = $width . 'pt';
1129
1130
							// We must also explicitly write the height of the <td> element because TCPDF
1131
							// does not recognize e.g. <tr style="height:50pt">
1132
							if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
1133
								$height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
1134
								$cssClass['height'] = $height;
1135
							}
1136
							//** end of redundant code **
1137
1138
							$html .= ' style="' . $this->_assembleCSS($cssClass) . '"';
0 ignored issues
show
Bug introduced by
It seems like $cssClass defined by 'column' . $colNum on line 997 can also be of type string; however, PHPExcel_Writer_HTML::_assembleCSS() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1139
						}
1140
						if ($colSpan > 1) {
1141
							$html .= ' colspan="' . $colSpan . '"';
1142
						}
1143
						if ($rowSpan > 1) {
1144
							$html .= ' rowspan="' . $rowSpan . '"';
1145
						}
1146
					$html .= '>';
1147
1148
					// Image?
1149
					$html .= $this->_writeImageTagInCell($pSheet, $coordinate);
1150
1151
					// Cell data
1152
					$html .= $cellData;
1153
1154
					// Column end
1155
					$html .= '</td>' . PHP_EOL;
1156
				}
1157
1158
				// Next column
1159
				++$colNum;
1160
			}
1161
1162
			// Write row end
1163
			$html .= '		  </tr>' . PHP_EOL;
1164
1165
			// Return
1166
			return $html;
1167
		} else {
1168
			throw new Exception("Invalid parameters passed.");
1169
		}
1170
	}
1171
1172
	/**
1173
	 * Takes array where of CSS properties / values and converts to CSS string
1174
	 *
1175
	 * @param array
1176
	 * @return string
1177
	 */
1178
	private function _assembleCSS($pValue = array())
1179
	{
1180
		$pairs = array();
1181
		foreach ($pValue as $property => $value) {
1182
			$pairs[] = $property . ':' . $value;
1183
		}
1184
		$string = implode('; ', $pairs);
1185
1186
		return $string;
1187
	}
1188
1189
	/**
1190
	 * Get Pre-Calculate Formulas
1191
	 *
1192
	 * @return boolean
1193
	 */
1194
	public function getPreCalculateFormulas() {
1195
		return $this->_preCalculateFormulas;
1196
	}
1197
1198
	/**
1199
	 * Set Pre-Calculate Formulas
1200
	 *
1201
	 * @param boolean $pValue	Pre-Calculate Formulas?
1202
	 * @return PHPExcel_Writer_HTML
1203
	 */
1204
	public function setPreCalculateFormulas($pValue = true) {
1205
		$this->_preCalculateFormulas = $pValue;
1206
		return $this;
1207
	}
1208
1209
	/**
1210
	 * Get images root
1211
	 *
1212
	 * @return string
1213
	 */
1214
	public function getImagesRoot() {
1215
		return $this->_imagesRoot;
1216
	}
1217
1218
	/**
1219
	 * Set images root
1220
	 *
1221
	 * @param string $pValue
1222
	 * @return PHPExcel_Writer_HTML
1223
	 */
1224
	public function setImagesRoot($pValue = '.') {
1225
		$this->_imagesRoot = $pValue;
1226
		return $this;
1227
	}
1228
1229
	/**
1230
	 * Get use inline CSS?
1231
	 *
1232
	 * @return boolean
1233
	 */
1234
	public function getUseInlineCss() {
1235
		return $this->_useInlineCss;
1236
	}
1237
1238
	/**
1239
	 * Set use inline CSS?
1240
	 *
1241
	 * @param boolean $pValue
1242
	 * @return PHPExcel_Writer_HTML
1243
	 */
1244
	public function setUseInlineCss($pValue = false) {
1245
		$this->_useInlineCss = $pValue;
1246
		return $this;
1247
	}
1248
1249
	/**
1250
	 * Add color to formatted string as inline style
1251
	 *
1252
	 * @param string $pValue Plain formatted value without color
1253
	 * @param string $pFormat Format code
1254
	 * @return string
1255
	 */
1256
	public function formatColor($pValue, $pFormat)
1257
	{
1258
		// Color information, e.g. [Red] is always at the beginning
1259
		$color = null; // initialize
1260
		$matches = array();
1261
1262
		$color_regex = '/^\\[[a-zA-Z]+\\]/';
1263
		if (preg_match($color_regex, $pFormat, $matches)) {
1264
			$color = str_replace('[', '', $matches[0]);
1265
			$color = str_replace(']', '', $color);
1266
			$color = strtolower($color);
1267
		}
1268
1269
		// convert to PCDATA
1270
		$value = htmlspecialchars($pValue);
1271
1272
		// color span tag
1273
		if ($color !== null) {
1274
			$value = '<span style="color:' . $color . '">' . $value . '</span>';
1275
		}
1276
1277
		return $value;
1278
	}
1279
1280
	/**
1281
	 * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
1282
	 */
1283
	private function _calculateSpans()
1284
	{
1285
		// Identify all cells that should be omitted in HTML due to cell merge.
1286
		// In HTML only the upper-left cell should be written and it should have
1287
		//   appropriate rowspan / colspan attribute
1288
		$sheetIndexes = $this->_sheetIndex !== null ?
1289
			array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1);
1290
1291
		foreach ($sheetIndexes as $sheetIndex) {
1292
			$sheet = $this->_phpExcel->getSheet($sheetIndex);
1293
1294
			$candidateSpannedRow  = array();
1295
1296
			// loop through all Excel merged cells
1297
			foreach ($sheet->getMergeCells() as $cells) {
1298
				list($cells, ) = PHPExcel_Cell::splitRange($cells);
1299
				$first = $cells[0];
1300
				$last  = $cells[1];
1301
1302
				list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first);
1303
				$fc = PHPExcel_Cell::columnIndexFromString($fc) - 1;
1304
1305
				list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last);
1306
				$lc = PHPExcel_Cell::columnIndexFromString($lc) - 1;
1307
1308
				// loop through the individual cells in the individual merge
1309
				$r = $fr - 1;
1310
				while($r++ < $lr) {
1311
					// also, flag this row as a HTML row that is candidate to be omitted
1312
					$candidateSpannedRow[$r] = $r;
1313
1314
					$c = $fc - 1;
1315
					while($c++ < $lc) {
1316
						if ( !($c == $fc && $r == $fr) ) {
1317
							// not the upper-left cell (should not be written in HTML)
1318
							$this->_isSpannedCell[$sheetIndex][$r][$c] = array(
1319
								'baseCell' => array($fr, $fc),
1320
							);
1321
						} else {
1322
							// upper-left is the base cell that should hold the colspan/rowspan attribute
1323
							$this->_isBaseCell[$sheetIndex][$r][$c] = array(
1324
								'xlrowspan' => $lr - $fr + 1, // Excel rowspan
1325
								'rowspan'   => $lr - $fr + 1, // HTML rowspan, value may change
1326
								'xlcolspan' => $lc - $fc + 1, // Excel colspan
1327
								'colspan'   => $lc - $fc + 1, // HTML colspan, value may change
1328
							);
1329
						}
1330
					}
1331
				}
1332
			}
1333
1334
			// Identify which rows should be omitted in HTML. These are the rows where all the cells
1335
			//   participate in a merge and the where base cells are somewhere above.
1336
			$countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
1337
			foreach ($candidateSpannedRow as $rowIndex) {
1338
				if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) {
1339
					if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
1340
						$this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
1341
					};
1342
				}
1343
			}
1344
1345
			// For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
1346
			if ( isset($this->_isSpannedRow[$sheetIndex]) ) {
1347
				foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) {
1348
					$adjustedBaseCells = array();
1349
					$c = -1;
1350
					$e = $countColumns - 1;
1351
					while($c++ < $e) {
1352
						$baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
1353
1354
						if ( !in_array($baseCell, $adjustedBaseCells) ) {
1355
							// subtract rowspan by 1
1356
							--$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
1357
							$adjustedBaseCells[] = $baseCell;
1358
						}
1359
					}
1360
				}
1361
			}
1362
1363
			// TODO: Same for columns
1364
		}
1365
1366
		// We have calculated the spans
1367
		$this->_spansAreCalculated = true;
1368
	}
1369
1370
}
1371