ExcelExport.php
2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace App\Support;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Vtiful\Kernel\Excel;
use Vtiful\Kernel\Format;
abstract class ExcelExport
{
/**
* @var string
*/
private string $fileName;
/**
* @var \Vtiful\Kernel\Excel
*/
protected Excel $fileObject;
/**
* @var \Illuminate\Database\Eloquent\Builder
*/
protected Builder $builder;
private function __construct()
{
$this->fileName = Str::random(32) . '.xlsx';
$this->fileObject = (new Excel(['path' => storage_path('excels')]))->constMemory($this->fileName, NULL, false);
}
/**
* @param string|NULL $name
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function download(string $name = NULL): BinaryFileResponse
{
$this->handle();
return response()->download($this->fileObject->output(), $name ?? $this->fileName)->deleteFileAfterSend();
}
/**
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return \App\Support\ExcelExport
*/
public static function withBuilder(Builder $builder): static
{
return (new static)->setBuilder($builder);
}
/**
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return \App\Support\ExcelExport
*/
private function setBuilder(Builder $builder): static
{
$this->builder = $builder;
return $this;
}
/**
* @param array $header
* @param string $range
* @return \App\Support\ExcelExport
*/
protected function setHeader(array $header, string $range = 'A1'): static
{
$format = new Format($this->fileObject->getHandle());
$headStyle = $format->align(Format::FORMAT_ALIGN_CENTER, Format::FORMAT_ALIGN_VERTICAL_CENTER)->background(0XF2F2F2)->bold()->toResource();
tap($this->fileObject, static fn(Excel $row) => $row->header($header)->setRow($range, 22, $headStyle));
return $this;
}
/**
* @param array $ranges
* @return \App\Support\ExcelExport
*/
public function setColumns(array $ranges): static
{
Arr::map($ranges, fn($val, $key) => $this->fileObject->setColumn($key, $val));
return $this;
}
/**
* @return void
*/
private function handle(): void
{
$this->beforeHandle();
$this->builder->chunk(1000, fn(Collection $collection) => $this->fileObject->data($collection->map(fn($item) => $this->setData($item))->toArray()));
$this->afterHandle();
}
abstract protected function setData($item): array;
protected function beforeHandle(): void { }
protected function afterHandle(): void { }
}