I am trying to import an excel file with 150+ sheets inside it, then by checking the excel sheet name, I want to replace the data inside or add new rows.
Initially I thought of using view to manually make all the design myself and just export them but it would be time consuming.
This is what I currently have.
<?php
namespace App\Http\Controllers;
use App\Imports\FirstSheetImport;
use App\Imports\WorkingPaperImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
class WorkingPaperExportController extends Controller
{
public function getExcelAndRewrite(Request $request)
{
$import = new FirstSheetImport('EA1');
$modifiedData = $import->getModifiedData();
return $modifiedData;
}
}
<?php
namespace App\Imports;
use App\Exports\TestExportEA1;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Events\AfterImport;
use PhpOffice\PhpSpreadsheet\IOFactory;
class FirstSheetImport implements ToCollection, WithHeadingRow
{
protected $sheetName;
protected $sheetIndex;
protected $modifiedData = [];
public function __construct($sheetName)
{
$this->sheetName = $sheetName;
}
public function collection(Collection $collection)
{
//
}
protected function getFilePath()
{
// Provide the path to your Excel file
return storage_path('/import/uptodateworkingpaper.xlsx');
}
protected function hasHeadingRow()
{
// Return true or false based on your needs
return true;
}
public function getModifiedData()
{
$spreadsheet = IOFactory::load($this->getFilePath());
$sheetNames = $spreadsheet->getSheetNames();
$sheetIndex = array_search($this->sheetName, $sheetNames);
$this->sheetIndex = $sheetIndex;
if ($sheetIndex !== false) {
$worksheet = $spreadsheet->getSheet($sheetIndex);
$rows = $worksheet->toArray();
return $rows;
}
// return $this->sheetIndex;
}
}
With the functions I have now., I am able to get the correct worksheet data but I am not sure where to go from there. Not even sure if this is a good way.
Any help or suggestions is appreciated.
PHP 7.3.33 Laravel Framework 8.75.0