Update Handle Multi Sheet Plan & Benefit
This commit is contained in:
85
app/Services/ImportService.php
Normal file
85
app/Services/ImportService.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user