How to read data from the specific sheet number from Maatwebsite/Laravel-Excel package? - excel

I am working on import excel data in Laravel framework and using Maatwebsite/Laravel-Excel package.
Now I have followed the steps but not getting any idea after reading package documentation, so I need help to read data from the second(2nd) sheet as I have multiple sheets in my excel file.
BillingDataImport
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class BillingDataImport implements ToCollection
{
/**
* #param Collection $collection
*/
public function collection(Collection $collection)
{
return $collection;
}
}
BillingController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\BillingDataImport;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Input;
class BillingController extends Controller
{
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$import = new BillingDataImport();
$rawData = Excel::toArray($import, $request->file('company_1'));
var_dump($rawData);
}
}
When I dump the code, I am getting data from the first(1st) sheet but I want to read second(2nd) sheet so can you please guide me as I am not too good Laravel and with this package.

You need to implement WithMultipleSheets interface in your import class. It will require you to add sheets method. You will include them like these;
public function sheets(): array
{
return [
0 => new FirstSheetImport(),
1 => new SecondSheetImport(),
];
}
Then you may select them by index. More info here

Related

how to make laravel export excel without model

i have already read laravel-export excel. but my project is different, where my project didn't have model. how to make export excel in laravel without make model? laravel8 and maatwebsite3
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExportExcel implements FromCollection
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
//
}
}
what should I type in export controller, exportexcel and the download button
You could always import using DB facade.
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
DB::table('users')->insert([
'email' => $row[0],
]);
}
}
Alternatively you would always create empty shell models, to do insertions. I often do this, if i have to cleanup wordpress data and want the Laravel facades for ease of use.
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $fillable = ['name'];
}
Which would enable the following from the documentation to work.
public function model(array $row)
{
return new User([
'name' => $row[0],
]);
}

Read specific sheet by name on import excel laravel

I have an excel with multiple sheets but i only want read one sheet:
My problem is that i have multiple sheets, and they do not have the same order or the same number of pages. Then, i must identify the sheet by name on my import class (laravel import).
Here is my import class:
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithEvents;
class ExecutedUPS implements WithMultipleSheets, WithEvents
{
private $nameSheetUPS = "LMS - F";
public function sheets(): array
{
$sheets = [];
//doesn't work for me
if($event->getSheet()->getTitle() === $this->nameSheetUPS){
$sheets[] = new SheetUPS();
}
return $sheets;
}
}
And here is my class "SheetUPS":
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class SheetUPS implements ToCollection
{
/**
* #param Collection $collection
*/
public function collection(Collection $collection)
{
//this i know do
}
}
Have you tried selecting the sheet by name as the documentation does?
//class ExecutedUPS
public function sheets(): array
{
return [
'LMS - F' => new SheetUPS(),
];
}

Maatwebsite / laravel give name to Worksheet in export

I am using Maatwebsite / laravel to export data , I need to rename the Worksheet ,
below my class :
<?php
namespace App\Exports;
use App\Models\Client;
use App\Models\Item;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
class ItemExport implements FromCollection, WithHeadings, ShouldAutoSize
{
protected $rows;
use Exportable;
public function __construct($client_id , $items , $company_name)
{
$this->client_id = $client_id;
$this->items = $items;
$this->company_name = $company_name;
}
public function collection()
{
$i = 1;
$client = Client::find($this->client_id);
$item_new= [];
foreach($this->items as $item){
$item_new[] = [$i++,
$this->company_name,
$this->item,
$client->client_name,
];
}
return collect($item_new);
}
public function title(): string
{
return $this->company_name;
}
public function headings(): array
{
return [
'#',
'Company',
'item',
'client',
];
}
}
but it seems the public function title(): string , not working .
i supposed that the title function will work , but seems no
any idea how to give name to Worksheet ?
thanks
So close. You just need to implement the WithTitle interface.
class ItemExport implements FromCollection, WithHeadings, WithTitle, ShouldAutoSize
An example is somewhat buried in the multiple sheets section of the documentation, but I can confirm it works for single sheets too.
https://docs.laravel-excel.com/3.1/exports/multiple-sheets.html#sheet-classes
Laravel-How to create multiple sheet in one excel file using maatwebsite/excel": "^3.1.
1st step: I created a multiple excel export file
php artisan make:export MultipleSheetExport
2nd Create a route and controller
In controller I have written this function
public function state_summary_export()
{
return Excel::download(new MultipleSheetExport, 'ADCC Summary.xlsx');
}
Note: 'ADCC Summary.xlsx' is my excel file name.
Don’t forget to add this facades in you controller
use App\Exports\MultipleSheetExport;
use Maatwebsite\Excel\Facades\Excel;
3rd step: Open MultipleSheetExport
<?php
namespace App\Exports;
use Illuminate\Support\Arr;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithTitle;
class MultipleSheetExport implements WithMultipleSheets
{
public function sheets(): array
{
$sheets = [
new StateSummaryExport(),
new BMRPerformanceExport(),
];
return $sheets;
}
}
4th step: Go to Child StateSummaryExport and add this given line.
class StateSummaryExport implements WithTitle
public function title(): string
{
return 'State Summary';
}
Note: ‘State Summary’ is your sheet name. Do the same in BMRPerformanceExport.
Thank you.

Class Illuminate\Bus\Dispatcher contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods

I am trying to use Laravel Jobs, and that worked for few times but now I am getting this error.
Class Illuminate\Bus\Dispatcher contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods
"message": "Class Illuminate\Bus\Dispatcher contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Contracts\Bus\QueueingDispatcher::findBatch, Illuminate\Contracts\Bus\QueueingDispatcher::batch, Illuminate\Contracts\Bus\Dispatcher::dispatchSync)",
"exception": "Symfony\Component\ErrorHandler\Error\FatalError",
"file": "D:\xampp8\htdocs\sa-new\laravel-develop\vendor\laravel\framework\src\Illuminate\Bus\Dispatcher.php",
"line": 13,
My controller code looks like this
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use App\Model\BccMapping;
use App\Jobs\ProcessUnmappedRequests;
public function processUnmappedRequests(Request $request){
ProcessUnmappedRequests::dispatch('3',$request);
}
While my Job's code looks like this.
<?php
namespace App\Jobs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Model\BccMapping;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessUnmappedRequests implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $request;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($id, $request)
{
$this->siteId = $request->get('siteId');
$this->mappingId = $request->get('mappingId');
$this->email = $request->get('originEmail');
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$unmappedRequests = DB::table('bcc')->where("EmailFrom", trim($this->email))->whereNull('BccMappingId')
->where('Archive',0)->get();
if($unmappedRequests->isNotEmpty()){
$mapping = BccMapping::where('id',$this->mappingId )->first();
if(!$mapping)
return false;
$mappingData = json_decode($mapping->mapping);
$keyword = $mapping->keyword;
foreach ($unmappedRequests as $key=>$bcc){
$bccKeyword = app('App\Http\Controllers\BccToolController')->getDomNodeValue($mappingData->keywordPath->path,$bcc->HTML);
var_dump($bccKeyword);die;
}
}else{
return false;
}
}
}
Currently I am using Laravel 7.0 and PHP 7.4.

Avoid Doctrine to return all entities

Using Symfony2 / doctrine2, while we use the find() function to get a specific object based on the entity selected if there are relations (like OneToMany), Doctrine return all other object.
For example :
$em = $this->get(
'doctrine.orm.entity_manager',
$request->getSession()->get('entity_manager')
);
$product = $em->getRepository('MyBundle:Product')->find($id);
The result on $product will be the Product object + other linked objects like (Store, Category, ...etc.)
How can we control doctrine to determinate which object we need to be returned.
I can use Querybuilder, but i am looking if there are any function all determinate.
Doctrine return all other object
This is not how it works, at least by default.
Doctrine uses what is called lazy loading.
From the official documentation, you have the following example:
<?php
/** #Entity */
class Article
{
/** #Id #Column(type="integer") #GeneratedValue */
private $id;
/** #Column(type="string") */
private $headline;
/** #ManyToOne(targetEntity="User") */
private $author;
/** #OneToMany(targetEntity="Comment", mappedBy="article") */
private $comments;
public function __construct {
$this->comments = new ArrayCollection();
}
public function getAuthor() { return $this->author; }
public function getComments() { return $this->comments; }
}
$article = $em->find('Article', 1);
And the following explanation:
Instead of passing you back a real Author instance and a collection of
comments Doctrine will create proxy instances for you. Only if you
access these proxies for the first time they will go through the
EntityManager and load their state from the database.
Reference: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entity-object-graph-traversal
More information about the topic: http://www.doctrine-project.org/blog/doctrine-lazy-loading.html
You can configure extra lazy associations to avoid loading of relations in general.
/**
* #ManyToMany(targetEntity="CmsUser", mappedBy="groups", fetch="EXTRA_LAZY")
*/
protected $property;

Resources