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