1
|
|
|
<?php |
2
|
|
|
namespace Serialize; |
3
|
|
|
require_once dirname(__FILE__).'/../vendor/autoload.php'; |
4
|
|
|
|
5
|
|
|
use PhpOffice\PhpSpreadsheet\Spreadsheet; |
6
|
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx; |
7
|
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xls; |
8
|
|
|
|
9
|
|
|
class ExcelSerializer extends SpreadSheetSerializer |
10
|
|
|
{ |
11
|
|
|
protected $types = array('xlsx', 'xls', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'); |
12
|
|
|
|
13
|
|
|
protected function setRowFromArray(&$sheat, $row, $array, $count = 0) |
14
|
|
|
{ |
15
|
|
|
if($count === 0) |
16
|
|
|
{ |
17
|
|
|
$count = count($array); |
18
|
|
|
} |
19
|
|
View Code Duplication |
for($i = 0; $i < $count; $i++) |
|
|
|
|
20
|
|
|
{ |
21
|
|
|
if(isset($array[$i])) |
22
|
|
|
{ |
23
|
|
|
$sheat->setCellValueByColumnAndRow($i+1, $row, $array[$i]); |
24
|
|
|
} |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function serializeData(&$type, $array) |
29
|
|
|
{ |
30
|
|
|
if($this->supportsType($type) === false) |
31
|
|
|
{ |
32
|
|
|
return null; |
33
|
|
|
} |
34
|
|
|
$data = $this->getArray($array); |
35
|
|
|
$ssheat = new Spreadsheet(); |
36
|
|
|
$sheat = $ssheat->getActiveSheet(); |
37
|
|
|
$keys = array_shift($data); |
38
|
|
|
$rowCount = count($data); |
39
|
|
|
$colCount = count($keys); |
40
|
|
|
$this->setRowFromArray($sheat, 1, $keys, $colCount); |
41
|
|
|
for($i = 0; $i < $rowCount; $i++) |
42
|
|
|
{ |
43
|
|
|
$this->setRowFromArray($sheat, (2 + $i), $data[$i], $colCount); |
44
|
|
|
} |
45
|
|
|
$writerType = 'Excel5'; |
|
|
|
|
46
|
|
|
if(strcasecmp($type, 'xlsx') === 0 || strcasecmp($type, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') === 0) |
47
|
|
|
{ |
48
|
|
|
$writer = new Xlsx($ssheat); |
49
|
|
|
$writerType = 'Excel2007'; |
|
|
|
|
50
|
|
|
$type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; |
51
|
|
|
} |
52
|
|
|
else |
53
|
|
|
{ |
54
|
|
|
$writer = new Xls($ssheat); |
55
|
|
|
$type = 'application/vnd.ms-excel'; |
56
|
|
|
} |
57
|
|
|
ob_start(); |
58
|
|
|
$writer->save('php://output'); |
59
|
|
|
return ob_get_clean(); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.