wi-events/classes/Spreadsheet.php

62 lines
1.7 KiB
PHP
Raw Normal View History

2023-03-22 21:13:12 +01:00
<?php
namespace Zoomyboy\Event\Classes;
use PhpOffice\PhpSpreadsheet\Spreadsheet as BaseSpreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Spreadsheet
{
private array $headers;
private $sheet;
public function __construct(string $title)
{
$this->spreadsheet = new BaseSpreadsheet();
$this->spreadsheet->getProperties()
->setTitle($title)
->setSubject($title)
->setDescription($title);
$this->spreadsheet->getActiveSheet()->setTitle('unfilled');
}
public function headers(array $headers): self
{
$this->headers = $headers;
return $this;
}
public function generate()
{
$this->spreadsheet->setActiveSheetIndex(0);
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($this->spreadsheet);
$writer->save('/home/pille/s.xlsx');
$this->spreadsheet->disconnectWorksheets();
unset($this->spreadsheet);
}
public function sheet(string $name, array $data): self
{
if ('unfilled' === $this->spreadsheet->getActiveSheet()->getTitle()) {
$this->spreadsheet->getActiveSheet()->setTitle($name);
return $this->fill($data);
}
$this->spreadsheet->addSheet(new Worksheet($this->spreadsheet, $name));
$this->spreadsheet->setActiveSheetIndexByName($name);
return $this->fill($data);
}
private function fill(array $data): self
{
$headers = collect($this->headers)->map(fn ($header) => $header->name)->toArray();
$this->spreadsheet->getActiveSheet()->fromArray($headers, null, 'A1');
$this->spreadsheet->getActiveSheet()->fromArray($data, null, 'A2');
return $this;
}
}