rap2hpoutre / fast-excel

🦉 Fast Excel import/export for Laravel
MIT License
2.09k stars 246 forks source link

Import a Sheet by its Number or Name - suggested simple solution #273

Open volei opened 2 years ago

volei commented 2 years ago

Suggestion

At least for Excel, if you change line 47 of the trait importable.php in import() to

if ($this->sheet_number[0] != $sheet->getIndex()+1 &&
                $this->sheet_number[1] != $sheet->getName()) {

you can import by sheet name if your import call is, e.g.:

$importedModelCount = (new FastExcel)
            ->sheet([$no, $name])   // array: given sheet no. and sheet name
            ->import($file, function ($line) use ($model){
                       return $model::create($lineZero);  // actual import
             })
             ->count();

Result

The above combination logic in the new line 47 imports if, either the given sheet no., or the sheet name match a sheet in the import file. You may want to set $no=0 to prevent an unforeseable state and call only by sheet name, or vice versa, or use a different consistency logic altogether, e.g. include a toggle switch in the array. Preferably your toggle logic resides in your calling logic and you use the toggle switch. In this case you would call by

... ->sheet([$noOrName, $no, $name]) ...

Suggested usage

In your calling method you may then run your list of sheet names to load all your models, first loading the models and then their relationships - just in the same sequence as you would use with migrations. I have an Excel file with all my prepared model and relation tables filled with their respective entries. If you are able to receive well-ordered model sheets, e.g. from each salesperson, with correct relationship refs, you can set up the relationship tables easily by hand, before loading and running your Laravel app to spill out the monthly result.

Have fun!

PS: Is the suggested change in line 47 importable.php worth a pull request? As this is a one-time call for each sheet, I guess performance is not changed.