Laravel Excel import from few sheets - excel

I have a problem importing from several sheets at once, in one of them I have data that I need to compare with the data in the other sheet and then upload to the database.
I use Laravel Excel and read the documentation several times but I still can't find a reasonable solution. I do not want to split sheets and only be able to use the data from the sheets at the same time.
class FameImport implements WithMultipleSheets
{
public function sheets(): array {
return [
1 => new LabelSheet(),
2 => new DataSheet()
];
}
}
class LabelSheet implements ToCollection, WithStartRow, WithHeadingRow {
public function collection(Collection $collection)
{
return $collection;
}
public function startRow(): int
{
return 8;
}
}
class DataSheet implements ToCollection {
public function collection(Collection $collection)
{
dd($collection);
}
}

Related

Maatwebsite excel Serialization of 'PDO' is not allowed

Im tring to export large data in queue on s3 and getting Serialization of 'PDO' is not allowed exception/ Here is my code:
Controller
$transactions = Transaction::query()
->with([
'user',
'user.profile',
'senderUser',
'receiverUser',
'senderUser.roles',
'receiverUser.roles'
])->filterByUser()
->filter($filters)
->orderByDesc('created_at');
if (request()->export_transactions){
(new TransactionsExport(auth('sanctum')->user(),$transactions))->store('transactions-exports/' . now()->format('d:m:Y') . '.csv', 's3', \Maatwebsite\Excel\Excel::CSV);
return response()->json('Export started');
}
Export file
class TransactionsExport implements FromQuery, WithMapping, WithHeadings, WithCustomQuerySize, ShouldQueue
{
use Exportable;
private $user;
private $transactions;
public function __construct(User $user, $transactions)
{
$this->user = $user;
$this->transactions = $transactions;
}
/**
* #return Builder
*/
public function query()
{
return $this->transactions;
}
public function querySize(): int
{
return $this->transactions->count();
}
public function headings(): array
{
return [
//headings
];
}
public function prepareRows($transactions): array
{
//code here
}
public function map($transaction): array
{
//code here
}
}
I also tried to trigger it like this (with additional paramethers and without and with different allowed methods (store, download etc.))
(new TransactionsExport(auth('sanctum')->user(),$transactions))->queue('transactions-exports/' . now()->format('d:m:Y') . '.csv', 's3', \Maatwebsite\Excel\Excel::CSV);
Also, I tried move Transaction::query() direct to query method in export file.
Also didnt help toSql() method (Call to a member function count() on string exception appears)
Don't know what I'm doing wrong. Thanks for help.
I have solved the problem by deleting the injection of classes in the constructor, it's not allowed in jobs (queues/ if you need an object of a class, better to call it like new Class()), and now all is working fine.

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.

Method with dynamic return value to get all rows from a specific table

I have many of the following methods in my class for the data access:
public IEnmuerable<Customer> GetAllCustomer()
{
return MyEFContext.tblCustomer;
}
public IEnmuerable<Company> GetAllCompanies()
{
return MyEFContext.tblCompany;
}
public IEnmuerable<Car> GetAllCars()
{
return MyEFContext.tblCar;
}
...
Is there a way to define a method with a dynamic return value that gives me all rows from a specific table. So that I can call something like this:
List<Customer> allCustomers = GetAll<Customer>().ToList();
I searched a lot but found nothing usefull. My last Code was this, but it also fails:
public IEnumerable<T> GetAll<T>()
{
return MyEFContext.Set<T>();
}
After many try and errors, here comes my solution:
public IEnumerable<T> GetAll<T>()
{
return MyEFContext.Set(typeof(T)) as IEnumerable<T>;
}
Now I can call this method like:
List<Customer> allMyCustomers = GetAll<Customer>().ToList();

Form: Avoid setting null to non submitted field

I've got a simple model (simplified of source):
class Collection
{
public $page;
public $limit;
}
And a form type:
class CollectionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('page', 'integer');
$builder->add('limit', 'integer');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FSC\Common\Rest\Form\Model\Collection',
));
}
}
My controller:
public function getUsersAction(Request $request)
{
$collection = new Collection();
$collection->page = 1;
$collection->limit = 10;
$form = $this->createForm(new CollectionType(), $collection)
$form->bind($request);
print_r($collection);exit;
}
When i POST /users/?form[page]=2&form[limit]=20, the response is what i expect:
Collection Object
(
[page:public] => 2
[limit:public] => 20
)
Now, when i POST /users/?form[page]=3, the response is:
Collection Object
(
[page:public] => 3
[limit:public] =>
)
limit becomes null, because it was not submitted.
I wanted to get
Collection Object
(
[page:public] => 3
[limit:public] => 10 // The default value, set before the bind
)
Question: How can i change the form behaviour, so that it ignores non submitted values ?
If is only a problem of parameters (GET parameters) you can define the default value into routing file
route_name:
pattern: /users/?form[page]={page}&form[limit]={limit}
defaults: { _controller: CompanyNameBundleName:ControllerName:ActionName,
limit:10 }
An alternative way could be to use a hook (i.e. PRE_BIND) and update manually that value into this event. In that way you haven't the "logic" spreaded into multi pieces of code.
Final code - suggested by Adrien - will be
<?php
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class IgnoreNonSubmittedFieldSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_BIND => 'preBind');
}
public function preBind(FormEvent $event)
{
$submittedData = $event->getData();
$form = $event->getForm();
// We remove every child that has no data to bind, to avoid "overriding" the form default data
foreach ($form->all() as $name => $child) {
if (!isset($submittedData[$name])) {
$form->remove($name);
}
}
}
}
Here's a modification of the original answer. The most important benefit of this solution is that validators can now behave as if the form post would always be complete, which means there's no problems with error bubbling and such.
Note that object field names must be identical to form field names for this code to work.
<?php
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class FillNonSubmittedFieldsWithDefaultsSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_BIND => 'preBind');
}
public function preBind(FormEvent $event)
{
$submittedData = $event->getData();
$form = $event->getForm();
// We complete partial submitted data by inserting default values from object
foreach ($form->all() as $name => $child) {
if (!isset($submittedData[$name])) {
$obj = $form->getData();
$getter = "get".ucfirst($name);
$submittedData[$name] = $obj->$getter();
}
}
$event->setData($submittedData);
}
}

Resources