Laravel PhpSpreadsheet Multiple Table Import - php

i want to ask, is it possible to import excel excel to import
to the database like database table in php laravel?

of course there is a excelent package for import and export data from excel
Laravel-Excel
here is an example for export excel
class PermissionExport implements FromCollection, ShouldQueue , WithMapping , WithHeadings, WithEvents
{
public function registerEvents(): array
{
return [
BeforeSheet::class =>function(BeforeSheet $event){
$event->getDelegate()->setRightToLeft(true);
}
];
}
public function collection()
{
return Permission::all();
}
public function map($permissions): array
{
return [
$permissions->name,
$permissions->label,
];
}
public function headings(): array
{
return [
'permission name',
'permission description',
];
}
}
and here is and example for import data from excel
class PermissionsImport implements ToModel,WithStartRow
{
/**
* #param Collection $collection
*/
public function model(array $row)
{
return new permission([
'name' => $row[0],
'label' => $row[1],
]);
}
public function startRow(): int
{
return 2;
}
}

Related

get data after save excel file with `maatwebsite/excel`

Project in Laravel (9), and PHP (8.1).
I want to import an excel file and use maatwebsite/excel (3.1) package.
I can import a file, and save the file into the model, like this:
import class:
class BankTransfersHistoryImport implements ToModel, WithHeadingRow, WithValidation
{
use Importable;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new BankTransfersHistory([
'loanId' => $row['loanId'],
'actionDate' => transformDate($row['actionDate']),
'worth' => $row['worth'],
.
.
]);
}
public function headingRow(): int
{
return 2;
}
public function rules(): array
{
return [
'*.loanId' => ['required', 'numeric'],
... some roles ...
];
}
}
controller:
$import = new BankTransfersHistoryImport;
try {
// date validation
$collection = $import->toCollection($file);
... some validation about the date ...
$import->import($file);
... check and update rows ...
return [
"message" => some message,
"data" => [
some data
],
];
} catch (\Maatwebsite\Excel\Validators\ValidationException$e) {
$failures = $e->failures();
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
return $failures;
}
My question is:
If I can get the response of the file after saving the data, and that will give me the data with the id of the row that was saved.
In some cases, I will have to update a row. That's why I would like to get the ID.
Now in the check and update rows section, I update by loanId + actionDate. I want it to be done by ID.
something like this:
code:
$data = $import->import($file);
data will be like:
[
{
"id": 1,
"loanId": 21001,
"actionDate": "2020-01-02T00:00:00.000000Z",
"worth": 2997.09,
"offerId": 1,
},
{
"id": 2,
"loanId": 21002,
"actionDate": "2020-01-02T00:00:00.000000Z",
"worth": 3000,
"offerId": 10,
},
]
You can create a function on import class which will return the imported data, adding a sample for your reference.
UsersImport.php
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
private $rows;
public function __construct() {
$this->rows = collect();
}
/**
* #param array $row
*
* #return User|null
*/
public function model(array $row)
{
$user = new User([
'name' => $row[0],
'email' => $row[1],
'password' => bcrypt(12345678),
]);
$this->rows->push($user);
return $user;
}
/**
* Returns Imported Data
*
* #return \Illuminate\Support\Collection
*/
public function getImportedData(): \Illuminate\Support\Collection
{
return $this->rows;
}
}
Your Import Function in Controller
public function import(UsersImport $usersImport)
{
Excel::import($usersImport, public_path('users.xlsx'));
$usersImport->getImportedData();
}

How to create a new column when exporting a table. Laravel maatwebsite / excel

Please tell me, how create a new column when exporting(to exel) table. There is a table in DB of this kind:
I installed package for export maatwebsite / excel. There is also a my file of model:
class ScheduledInspectionModel extends Model
{
protected $table = 'scheduled_inspection'; // table name
protected $fillable = ['name_smp', 'name_control', "verification_start", "verification_end", 'verification_duration'];
public $timestamps = false;
}
Controller:
class OrganizationsExportController extends Controller
{
public function export()
{
return (new OrganizationsExport)->download('organizations_export.xls');
}
}
And file with export description:
class OrganizationsExport implements FromCollection, ShouldAutoSize, WithHeadings, WithEvents
{
use Exportable;
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return ScheduledInspectionModel::all();
}
public function headings(): array
{
return [
'id',
'Name SMP',
'Name Control',
'Verification Start',
'Verification End',
'Verification Duration'
];
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$event->sheet->getStyle('A1:F1')->applyFromArray([
'font' => [
'bold' => true
]
]);
}
];
}
}
The exported table looks like this:
The export works :) But I want to create in place of the 'id' column (I can exclude it using map ()), 'Number' column and enter the line numbering accordingly. Please tell me how to do this?
I would use the map() function on the export, here you can tweak the source of each column. I assumed column names in your db, due to not knowing the structure. Add one to the count each time it is transformed and you should be golden, which is done with the ++ operator.
private $count = 0;
public function map(ScheduledInspectionModel $inspection): array
{
return [
++$this->count,
$inspection->name_smp,
$inspection->name_control,
$inspection->verification_start->format('Y-m-d') . ' - ' .$inspection->verification_end->format('Y-m-d'),
$inspection->duration,
];
}
To call format on dates, you have to set the dates array on your model.
class ScheduledInspectionModel {
protected $dates = [
'verification_start',
'verification_end',
];
}

Laravel: How to change Time Stamps Format in Excel Export?

I am generating a Excel Export, I want to change the timestamps format in excel file from 2020-07-29 13:56:09 to just DD:MM:YYYY.
How can I change my Export Class to Format the timestamp Column in my Excel File, BTW Date is in 'E' column in Excel file.
My Export Class:
use App\outbound_detail;
use App\outbound_temp;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Events\AfterSheet;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
protected $reference;
function __construct($reference)
{
$this->reference = $reference;
}
public function collection()
{
return outbound_detail::where('reference', $this->reference)->get([
'reference', 'sku_parent', 'sku_child', 'cases', 'updated_at'
]);
}
public function headings(): array
{
return [
'Reference',
'SKU Parent',
'SKU Child',
'Cases Released',
'Date Created'
];
}
// ...
/**
* #return array
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}
}
On your Reference Model, add this :
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d:m:Y');
}
You can use it's column formatting.
Try this:
// ...
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents, WithColumnFormatting
{
// ...
public function map($reference): array
{
return [
$reference->reference,
$reference->sku_parent,
$reference->sku_child,
$reference->cases,
Date::dateTimeToExcel($reference->updated_at)
];
}
public function columnFormats(): array
{
return [
'E' => NumberFormat::FORMAT_DATE_DDMMYYYY
];
}
}

Laravel: How change PDF styling in maatwebsite DOMPDF export?

I am exporting PDF files with every entry.
But they are too simple, i.e: no styling.
Here is a screenshot:
But as you can see, there is no styling other then the styling is used for my Excel export. I want to add a logo image on top. Remove the extra columns and add some header text like Company name, address etc....
Here is my Controller:
public function export_release(Request $request)
{
Excel::store(new \App\Exports\ReleaseExportView($request->reference),'uploads/release/'.$request->reference.'/'.'release_'.$request->reference.'.pdf','real_public', \Maatwebsite\Excel\Excel::DOMPDF);
return redirect()->route('release_inventory')->with('success','Outbound has been Created.');
}
Here is my Export class:
use App\outbound_detail;
use App\outbound_temp;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
protected $reference;
function __construct($reference) {
$this->reference = $reference;
}
public function collection()
{
//link for StackOverFlow
//https://stackoverflow.com/questions/57153985/how-to-pass-parameter-to-export-file-of-laravel-excel-for-db-query
return outbound_detail::where('reference',$this->reference)->get([
'reference', 'sku_parent', 'sku_child', 'cases'
]);
}
public function headings(): array
{
return [
'Reference',
'SKU Parent',
'SKU Child',
'Cases Released'
];
}
// ...
/**
* #return array
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}
}
First of all Remove ShouldAutoSize, to fit the data in your file.
Then edit A1:W1 in AfterSheet. I'm still researching on adding company info also
you can return Blade view instead of array and customize the layout there
public function view(): View
{
$data = [];
return view('yourBladeView', [
'details' => $data
]);
}

how to skip the row about importing excel laravel with the Maatwebsite/Laravel-Excel

I have a problem to skip the row about importing excel laravel with the Maatwebsite / Laravel-Excel package.
I tried many ways from the internet but it still didn't work.
this is my controller code
if ($request->hasFile('file')) {
$import = new HsatuImport();
$file = $request->file('file'); //GET FILE
// config(['excel.import.startRow' => 2]);
Excel::import($import, $file)->limit(false, 2); //IMPORT FILE
return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Berhasil '.$import->getRowCount().' Data');
} else {
return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Gagal');
}
and this is my import code
<?php
namespace App\Imports;
use App\Models\Hsatu;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\ToModel;
class HsatuImport implements ToModel
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
private $rows = 0;
public function model(array $row)
{
++$this->rows;
return new Hsatu([
'region' => #$row[0],
'nomor_faktur' => #$row[1],
'nomor_rangka' => #$row[2],
'kode_mesin' => #$row[3]
]);
}
public function headingRow(): int
{
return 1;
}
public function getRowCount(): int
{
return $this->rows;
}
}
I had the problem with skipping when there's already existing Eloquent model. So below my code:
public function model(array $row)
{
$name = $row['name'];
if (!Category::where('name', $name)->exists())
return new Category([
'name' => $name
]);
}
I'm returning Model instance only if given statement is true.

Categories