1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\SimpleExcel; |
4
|
|
|
|
5
|
|
|
use Box\Spout\Writer\WriterInterface; |
6
|
|
|
use Box\Spout\Common\Entity\Style\Style; |
7
|
|
|
use Box\Spout\Writer\Common\Creator\WriterEntityFactory; |
8
|
|
|
|
9
|
|
|
class SimpleExcelWriter |
10
|
|
|
{ |
11
|
|
|
/** @var \Box\Spout\Writer\WriterInterface */ |
12
|
|
|
private $writer; |
13
|
|
|
|
14
|
|
|
private $path = ''; |
15
|
|
|
|
16
|
|
|
private $processHeader = true; |
17
|
|
|
|
18
|
|
|
private $processingFirstRow = true; |
19
|
|
|
|
20
|
|
|
private $numberOfRows = 0; |
21
|
|
|
|
22
|
|
|
public static function create(string $file) |
23
|
|
|
{ |
24
|
|
|
return new static($file); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function __construct(string $path) |
28
|
|
|
{ |
29
|
|
|
$this->writer = WriterEntityFactory::createWriterFromFile($path); |
30
|
|
|
|
31
|
|
|
$this->path = $path; |
32
|
|
|
|
33
|
|
|
$this->writer->openToFile($this->path); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function getPath(): string |
37
|
|
|
{ |
38
|
|
|
return $this->path; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function getWriter(): WriterInterface |
42
|
|
|
{ |
43
|
|
|
return $this->writer; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function getNumberOfRows(): int |
47
|
|
|
{ |
48
|
|
|
return $this->numberOfRows; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function noHeaderRow() |
52
|
|
|
{ |
53
|
|
|
$this->processHeader = false; |
54
|
|
|
|
55
|
|
|
return $this; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param \Box\Spout\Common\Entity\Row|array $row |
60
|
|
|
* @param \Box\Spout\Common\Entity\Style\Style|null $style |
61
|
|
|
*/ |
62
|
|
|
public function addRow($row, Style $style = null) |
63
|
|
|
{ |
64
|
|
|
if (is_array($row)) { |
65
|
|
|
if ($this->processHeader && $this->processingFirstRow) { |
66
|
|
|
$this->writeHeaderFromRow($row); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$row = WriterEntityFactory::createRowFromArray($row, $style); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$this->writer->addRow($row); |
73
|
|
|
$this->numberOfRows++; |
74
|
|
|
|
75
|
|
|
$this->processingFirstRow = false; |
76
|
|
|
|
77
|
|
|
return $this; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
protected function writeHeaderFromRow(array $row) |
81
|
|
|
{ |
82
|
|
|
$headerValues = array_keys($row); |
83
|
|
|
|
84
|
|
|
$headerRow = WriterEntityFactory::createRowFromArray($headerValues); |
85
|
|
|
|
86
|
|
|
$this->writer->addRow($headerRow); |
87
|
|
|
$this->numberOfRows++; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
public function close() |
91
|
|
|
{ |
92
|
|
|
$this->writer->close(); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
public function __destruct() |
96
|
|
|
{ |
97
|
|
|
$this->close(); |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|