How to insert Custom row Laravel excel collection - laravel

I trying to export a Excel file, from a collection using laravel. The code bellow, returns me this. I need to add a 2 new rows above the start of columsn, is that possible? What Should I do?
<?php
namespace App\Traits;
namespace App\Exports;
// use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
class exportSafety implements FromCollection, WithHeadings, WithMapping, WithColumnWidths, WithStyles, WithColumnFormatting, WithCustomStartCell
{
protected $services;
protected $request;
public function __construct(Collection $services)
{
$this->services = $services;
}
public function startCell(): string
{
return 'A3';
}
public function columnWidths(): array
{
return [
'A' => 30,
'B' => 20,
'C' => 20,
'D' => 15,
];
}
public function columnFormats(): array
{
return [
'B' => NumberFormat::FORMAT_DATE_DDMMYYYY,
];
}
public function styles(Worksheet $sheet)
{
return [
// Style the first row as bold text.
3 => ['font' => ['bold' => true]],
];
}
public function collection()
{
$this->services->each(function ($service) {
$this->map($service);
});
return $this->services;
}
public function headings(): array
{
$columns = [
'Name' => 'Name',
'Data de Nascimento' => 'Data de Nascimento',
'CPF' => 'CPF',
'Valor do Seguro' => "Valor do Seguro"
];
return $columns;
}
public function startRow(): int
{
return 2;
}
public function map($service): array
{
$columns = [
'Name' => $service->name,
'Data de Nascimento' => $service->birthdate,
'CPF' => $service->cpf,
'Valor do Seguro' => $service->client->donation_safety
];
return $columns;
}
}
But I need something like this:
I need to put two custom row above the start of the columns, is that possible? How I to that? I am using https://docs.laravel-excel.com/3.1/imports/multiple-sheets.html

you need to use WithHeadings trait to format heading rows.
$rangeHeadings = [
'chiqaruvchi',
'chiqarilgan',
'sotilgan',
"sana",
];
public function headings(): array
{
return [
[
$this->product?->name . " product " . $this->params['from_date'] . ' - ' . $this->params['to_date'] . " report",
],
$rangeHeadings,
];
}

Related

How to skip row after headings laravel excel

I just want to make the row of datas will rendered after headings
This's the result that i want
this what i want
But i only get this result
this i get
I already using startRow and set to 7, but nothing change
I have 6 row of heading, so how to render/display the data after headings, and i already return another collection with another model, but the result is same there's nothing change, the data keep displayed from first row
<?php
namespace App\Exports;
Importing Models...
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithEvents;
class TahapSeleksiExport implements FromCollection, WithHeadings, WithColumnWidths, WithStyles, WithEvents
{
use RegistersEventListeners;
protected $id;
function __construct($id) {
$this->id = $id;
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
$tahap = Tahap::where('id_tahap', $this->id)->first();
if ($tahap->status == '0') {
if ($tahap->tahap_ke == '1') {
return Pelamar::select('pelamar.id_pelamar', 'alm.nama', 'jur.akronim', 'ang.angkatan', 'pelamar.tanggal_kirim')
->where('lowongankerja_id', $tahap->lowongankerja_id)
->join('alumni_mendaftar_pelamar as almPel', 'almPel.pelamar_id', '=','pelamar.id_pelamar')
->join('alumni as alm', 'almPel.alumni_id', '=','alm.id_alumni')
->join('jurusan as jur', 'alm.jurusan_id', '=','jur.id_jurusan')
->join('angkatan as ang', 'alm.angkatan_id', '=','ang.id_angkatan')
->orderBy('pelamar.tanggal_kirim')
->orderBy('jur.akronim')
->orderBy('ang.angkatan', 'DESC')
->get();
}else{
return SeleksiPelamar::select('pelamar.id_pelamar', 'alm.nama', 'jur.akronim', 'ang.angkatan', 'pelamar.tanggal_kirim')
->where('lowongankerja_id', $tahap->lowongankerja_id)
->join('pelamar', 'pelamar.id_pelamar', '=','seleksi_pelamar.pelamar_id')
->join('alumni_mendaftar_pelamar as almPel', 'almPel.pelamar_id', '=','pelamar.id_pelamar')
->join('alumni as alm', 'almPel.alumni_id', '=','alm.id_alumni')
->join('jurusan as jur', 'alm.jurusan_id', '=','jur.id_jurusan')
->join('angkatan as ang', 'alm.angkatan_id', '=','ang.id_angkatan')
->orderBy('pelamar.tanggal_kirim')
->orderBy('jur.akronim')
->orderBy('ang.angkatan', 'DESC')
->where('keterangan', '1')->whereHas('tahap', function ($tahaps) use ($tahap) {
$tahaps->where('lowongankerja_id', $tahap->lowongankerja_id)->where('tahap_ke', $tahap->tahap_ke - 1);
})->get();
}
}
}
public function columnWidths(): array
{
return [
'A' => 15,
'B' => 40,
'C' => 15,
'D' => 15,
'E' => 25,
'F' => 12,
];
}
public function styles(Worksheet $sheet)
{
$sheet->getStyle(2)->getFont()->setBold(true);
$sheet->mergeCells('A2:G2');
$sheet->mergeCells('A3:G3');
$sheet->mergeCells('A4:G4');
}
public static function afterSheet(AfterSheet $event)
{
$sheet = $event->sheet->getDelegate();
$sheet->getStyle(2)->getFont()->setSize(16);
$sheet->getStyle(3)->getFont()->setSize(14);
$sheet->getStyle(4)->getFont()->setSize(14);
$sheet->getStyle('A6:G6')->getFont()
->setBold(true)
->getColor()->setRGB('ffffff');
$sheet->getStyle('A6:G6')->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setARGB('2041BB');
}
public function headings():array
{
$tahap = Tahap::where('id_tahap', $this->id)->first();
return [ // PER ROW HEADINGNYA
[], [$tahap->nama], ['Seleksi Alumni'], ['BKK SMKN 1 Kota Bekasi'],[],[
'ID Pelamar',
'Nama',
'Jurusan',
'Angkatan',
'Tanggal Submit',
'Nilai',
'Lulus',
]
];
}
}
The easy solution is to add an empty array of data to the collection. The solution is not idle but I think it can works. Try this:
public function collection()
{
$tahap = Tahap::where('id_tahap', $this->id)->first();
$PelamarData = new Collection();
if ($tahap->status == '0') {
if ($tahap->tahap_ke == '1') {
$PelamarData = Pelamar::select('pelamar.id_pelamar', 'alm.nama', 'jur.akronim', 'ang.angkatan', 'pelamar.tanggal_kirim')
->where('lowongankerja_id', $tahap->lowongankerja_id)
->join('alumni_mendaftar_pelamar as almPel', 'almPel.pelamar_id', '=','pelamar.id_pelamar')
->join('alumni as alm', 'almPel.alumni_id', '=','alm.id_alumni')
->join('jurusan as jur', 'alm.jurusan_id', '=','jur.id_jurusan')
->join('angkatan as ang', 'alm.angkatan_id', '=','ang.id_angkatan')
->orderBy('pelamar.tanggal_kirim')
->orderBy('jur.akronim')
->orderBy('ang.angkatan', 'DESC')
->get();
}else{
$PelamarData = SeleksiPelamar::select('pelamar.id_pelamar', 'alm.nama', 'jur.akronim', 'ang.angkatan', 'pelamar.tanggal_kirim')
->where('lowongankerja_id', $tahap->lowongankerja_id)
->join('pelamar', 'pelamar.id_pelamar', '=','seleksi_pelamar.pelamar_id')
->join('alumni_mendaftar_pelamar as almPel', 'almPel.pelamar_id', '=','pelamar.id_pelamar')
->join('alumni as alm', 'almPel.alumni_id', '=','alm.id_alumni')
->join('jurusan as jur', 'alm.jurusan_id', '=','jur.id_jurusan')
->join('angkatan as ang', 'alm.angkatan_id', '=','ang.id_angkatan')
->orderBy('pelamar.tanggal_kirim')
->orderBy('jur.akronim')
->orderBy('ang.angkatan', 'DESC')
->where('keterangan', '1')->whereHas('tahap', function ($tahaps) use ($tahap) {
$tahaps->where('lowongankerja_id', $tahap->lowongankerja_id)->where('tahap_ke', $tahap->tahap_ke - 1);
})->get();
}
//Add empty array data to skip the first 7 rows
foreach (range(1, 7) as $item)
{
$PelamarData->prepend([]);
}
return $PelamarData;
}
}

Laravel / OctoberCMS frontend filter

I am using OctoberCMS and I have created a custom component. I am trying to create a frontend filter to filter Packages by the Tour they are assigned to.
This is what I have so far. The issue is that the code is looking for a tour field within the packages table rather than using the tour relationship. Does anyone have any ideas?
<?php namespace Jakefeeley\Sghsportingevents\Components;
use Cms\Classes\ComponentBase;
use JakeFeeley\SghSportingEvents\Models\Package;
use Illuminate\Support\Facades\Input;
class FilterPackages extends ComponentBase
{
public function componentDetails()
{
return [
'name' => 'Filter Packages',
'description' => 'Displays filters for packages'
];
}
public function onRun() {
$this->packages = $this->filterPackages();
}
protected function filterPackages() {
$tour = Input::get('tour');
$query = Package::all();
if($tour){
$query = Package::where('tour', '=', $tour)->get();
}
return $query;
}
public $packages;
}
I really appreciate any help you can provide.
Try to query the relationship when the filter input is provided.
This is one way to do it;
public $packages;
protected $tourCode;
public function init()
{
$this->tourCode = trim(post('tour', '')); // or input()
$this->packages = $this->loadPackages();
}
private function loadPackages()
{
$query = PackagesModel::query();
// Run your query only when the input 'tour' is present.
// This assumes the 'tours' db table has a column named 'code'
$query->when(!empty($this->tourCode), function ($q){
return $q->whereHas('tour', function ($qq) {
$qq->whereCode($this->tourCode);
});
});
return $query->get();
}
If you need to support pagination, sorting and any additional filters you can just add their properties like above. e.g;
protected $sortOrder;
public function defineProperties(): array
{
return [
'sortOrder' => [
'title' => 'Sort by',
'type' => 'dropdown',
'default' => 'id asc',
'options' => [...], // allowed sorting options
],
];
}
public function init()
{
$filters = (array) post();
$this->tourCode = isset($filters['tour']) ? trim($filters['tour']) : '';
$this->sortOrder = isset($filters['sortOrder']) ? $filters['sortOrder'] : $this->property('sortOrder');
$this->packages = $this->loadPackages();
}
If you have a more complex situation like ajax filter forms or dynamic partials then you can organize it in a way to load the records on demand vs on every request.e.g;
public function onRun()
{
$this->packages = $this->loadPackages();
}
public function onFilter()
{
if (request()->ajax()) {
try {
return [
"#target-container" => $this->renderPartial("#packages",
[
'packages' => $this->loadPackages()
]
),
];
} catch (Exception $ex) {
throw $ex;
}
}
return false;
}
// call component-name::onFilter from your partials..
You are looking for the whereHas method. You can find about here in the docs. I am not sure what your input is getting. This will also return a collection and not singular record. Use ->first() instead of ->get() if you are only expecting one result.
$package = Package::whereHas('tour', function ($query) {
$query->where('id', $tour);
})->get();

array must be compatible with Maatwebsite\Excel\Concerns\WithMapping::map($row) in - Laravel

I am using Laravel-5.8 and Maatwebsite-3.1 to export to excel.
<?php
namespace App\Exports;
use App\User;
use Auth;
class StudentExport implements FromCollection, ShouldAutoSize, WithHeadings, WithMappings, WithCustomStartCell
{
private $headings = [
'Student ID',
'Name',
'Class',
'Status',
'Teacher'
];
public function collection()
{
$current_terms = DB::table('appraisal_identity')->select('term_name')->where('company_id', $userCompany)->where('is_current', 1)->first()->term_name;
$publishedgoals = AppraisalGoal::select('employee_code')->where('is_published', 1)->where('company_id', $userCompany)->groupBy('employee_code')->get();
$published_goals = DB::table('hr_students AS e')
->join('hr_employees AS em','em.id','=','e.teacher_id')
->select(
'e.student_id',
DB::raw('CONCAT(e.first_name, " ", e.last_name) AS full_name'),
'e.student_class,
DB::raw('(CASE WHEN e.is_status = 3 THEN "Excellent" WHEN e.is_status = 2 THEN "Good" WHEN e.is_status = 1 THEN "Average" ELSE "Pass" END) AS student_status')
DB::raw('CONCAT(em.first_name, " ", em.last_name) AS teacher_name')
)
->whereIn('e.student_id', $publishedgoals)
->distinct()
->get();
$published_goals = $published_goals->unique('student_id');
return collect($published_goals, $current_terms);
}
public function map($published_goals, $current_terms): array
{
return [
$published_goals->student_id,
$published_goals->full_name,
$published_goals->student_class,
$published_goals->student_status,
$published_goals->teacher_name,
$current_terms->term_name,
];
}
public function startCell(): string
{
return 'A4';
}
public function headings() : array
{
return $this->headings;
}
public function registerEvents() : array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$event->sheet->setCellValue('A2', 'Current Term:');
$event->sheet->getDelegate()->setCellValue('B2', $current_terms);
$cellRange = 'A4:E4'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->getColor()
->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$event->sheet->getDelegate()->getStyle($cellRange)->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setARGB('FF17a2b8');
$event->sheet->setAutoFilter($cellRange);
},
];
}
}
This is my expected output:
I have written the code above to get this result:
I want to make B2 to have the output of this variable: $current_terms
I got this error:
ERROR: Declaration of App\Exports\HrEmployeeGoalExport::map($published_goals, $current_terms): array must be compatible with Maatwebsite\Excel\Concerns\WithMapping::map($row)
How do I resolve this?
Thank you
Check the install docs for Laravel excel: https://docs.laravel-excel.com/3.1/getting-started/installation.html#installation
You probably need to run…
composer require psr/simple-cache:2.0 maatwebsite/excel
Enjoy !
You are implementing a number of the contracts from the Maatwebsite\Excel package, one of those contracts specifies that you must implement a map method that takes a $row as the argument; Maatwebsite\Excel\Concerns\WithMapping::map($row).
In your class you have HrEmployeeGoalExport::map($published_goals, $current_terms): array
To get this to work, you must change your map function to be HrEmployeeGoalExport::map($row) and then use $row to do any mapping.'
As such, you need to change the arguments you are receiving and remove the return type that you have specified.

how to change the format of the columns of csv exported- laravel excel

I exported a csv file with laravel-excel 3.1 and when reviewing the values are enclosed in quotes, so they are exported as strings, but I need it to be in type number
Exported csv file:
"ano_plantacion","zona","sitio","manejo","sup_ha","codigo","rpend"
"2018","87","3","10","30.69","2042201801",""
"2017","87","3","10","14.86","2042201701",""
What I want or should be:
ano_plantacion,zona,sitio,manejo,sup_ha,codigo,rpend
2018,87,3,10,30.69,2042201801,
2017,87,3,10,14.86,2042201701,
Class SuperImport:
<?php
namespace App\Exports;
use App\Super;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class SuperExport implements FromCollection,WithHeadings, WithColumnFormatting
{
use Exportable;
protected $superficie;
public function __construct($superficie = null)
{
$this->superficie = $superficie;
}
public function headings(): array
{
return [
'ano_plantacion',
'zona',
'sitio',
'manejo',
'sup_ha',
'codigo',
'rpend',
];
}
public function columnFormats(): array
{
return [
'A' => NumberFormat::FORMAT_GENERAL,
'B' => NumberFormat::FORMAT_GENERAL,
'C' => NumberFormat::FORMAT_GENERAL,
'D' => NumberFormat::FORMAT_GENERAL,
'E' => NumberFormat::FORMAT_GENERAL,
'F' => NumberFormat::FORMAT_GENERAL,
'G' => NumberFormat::FORMAT_GENERAL,
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return $this->superficie ?: Super::all();
}
}
Controller:
$super = Super::select('ano_plantacion','zona','sitio', 'manejo','sup_ha','codigo','rpend')->get();
Excel::store( new SuperExport($super), 'export/Super.csv' );
It is assumed that with the columnFormats() method it is possible to change the format, but I don't see in the documentation what format is available, and when executing the code the problem continues.
Help pls :(
I found another solution, instead of using laravel excel, I tried another library: https://github.com/rap2hpoutre/fast-excel
So was my controller:
(new FastExcel(Super::all()))->export(storage_path('app/export/SuperFast.csv'), function ($super) {
return [
'ano_plantacion' => $super->ano_plantacion,
'zona' => $super->zona,
'sitio' => $super->sitio,
'manejo' => $super->manejo,
'sup_ha' => $super->sup_ha,
'codigo' => $super->codigo,
'repend' => $super->repend,
];
});
This is how my csv was: http://prntscr.com/squjh5

How to manipulate data before exporting in laravel 5.7 and excel 3.1

I want to customize column names, concatinate data in one column. Can put some condition on data.
Below is sample image, In which format data would show. How to make possible this-
Here you can find how to manipulate columns names:
https://laravel-excel.maatwebsite.nl/3.1/exports/mapping.html
And below its a example from my project in how to use it. Enjoy!
namespace App\Exports;
use App\Aluno;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class AlunosExport implements FromCollection, WithStrictNullComparison, WithHeadings, ShouldAutoSize
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
$alunos = Aluno::all();
$dadosAluno = [];
foreach ($alunos as $aluno) {
$textoEtapas = '';
foreach ($aluno->etapas as $etapa) {
$textoEtapas .= "{$etapa->nome}";
if ($etapa->concluido) {
$textoEtapas .= ' (Concluído)';
}
$textoEtapas .= "\n";
}
$dadosAluno[] = [
'nome' => $aluno->cliente->nome,
'telefone' => formatarTelefone($aluno->cliente->telefone),
'instituicao' => $aluno->cliente->turma->unidade->instituicao->nome,
'turma' => $aluno->cliente->turma->nome,
'programa' => $aluno->programa->nome,
'etapas' => $textoEtapas,
'valor' => $aluno->valor,
'orientador' => !is_null($aluno->orientador) ? $aluno->orientador->nome : '(Excluído)',
'status' => $aluno->cliente->status
];
}
$alunoColection = collect($dadosAluno);
return $alunoColection;
}
public function headings(): array
{
return [
'Aluno',
'Telefone',
'Instituição',
'Turma',
'Programa',
'Etapas',
'Valor',
'Orientador',
'Status'
];
}
}

Resources