Files
aso/app/Services/ImportService.php
2023-07-03 11:39:08 +07:00

86 lines
1.9 KiB
PHP

<?php
namespace App\Services;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Illuminate\Support\Facades\Storage;
class ImportService{
public $reader;
public $writer;
public function read($filePath)
{
$this->reader = ReaderEntityFactory::createReaderFromFile($filePath);
$this->reader->open($filePath);
return $this;
}
public function readRow()
{
$row = $this->reader->getNextRow();
return $row;
}
public function sheetsIterator()
{
return $this->reader->getSheetIterator();
}
public function write($filePath, $format = 'xsls')
{
switch ($format) {
case 'xsls':
$this->writer = WriterEntityFactory::createXLSXWriter();
break;
case 'csv':
$this->writer = WriterEntityFactory::createCSVWriter();
break;
default:
throw new \Exception('Unknown format');
}
$this->writer->openToFile($filePath);
$this->format = $format;
return $this;
}
public function makeCells($array_row_data)
{
$cells = [];
foreach ($array_row_data as $cellValue) {
$cells[] = WriterEntityFactory::createCell($cellValue);
}
return $cells;
}
public function makeRow($array)
{
return WriterEntityFactory::createRow($this->makeCells($array));
}
public function addArrayToRow($array, $sheetName = null)
{
// Switch to the correct Sheet Before Write
if ($sheetName) {
if ($sheetName != $this->writer->getCurrentSheet()->getName()) {
foreach ($this->writer->getSheetIterator() as $sheet) {
if ($sheet->getName() == $sheet) {
$this->writer->setCurrentSheet($sheet);
break;
}
}
}
}
$newRow = $this->makeRow($array);
$this->writer->addRow($newRow);
return $this;
}
}