Home > Software design >  Laravel export Maatwebsite/Excel, restructuring the output
Laravel export Maatwebsite/Excel, restructuring the output

Time:03-30

Could somebody tell me how to reformat the excel output, so that i get two excel columns. Right now it gives me two arrays in A1 and B1. like two fields with [1,24,5,3.3] and [3,4,5,6], but I want two columns with the numbers.

Route

Route::get('/exporttable/{id}', [TableExportController::class, 'export']);

TableExportController

use Illuminate\Http\Request;
use App\Exports\TablesExport;
use Maatwebsite\Excel\Facades\Excel;

class TableExportController extends Controller
{
    public function export(Request $request){
        return Excel::download(new TablesExport($request->id), 'tables.xlsx');
    }
}

TableExport.php

use App\Models\Tabula;
use Maatwebsite\Excel\Concerns\FromCollection;

class TablesExport implements FromCollection
{

    /**
    * @return \Illuminate\Support\Collection
    */
    function __construct($id) {
        $this->id = $id;
    }

    public function collection()
    {
        $tabula = Tabula::select('soll',  'haben')->where('id', '=', $this->id)->get();

        return $tabula;
    }
}

CodePudding user response:

Make changes as per below in TableExport.php and check

<?php

namespace App\Exports;

use App\Models\Tabula;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMapping;

class TablesExport implements FromQuery, WithMapping
{
    use Exportable;

    public function __construct($id)
    {
        $this->id = $id;
    }

    public function query()
    {
        return Tabula::query()
            ->select('id', 'soll', 'haben')
            ->where('id', $this->id);
    }

    public function map($tabula): array
    {
        return [
            $tabula->soll,
            $tabula->haben
        ];
    }
}

CodePudding user response:

It works with the code of Natvarsinh Parmar - bapu , if you edit the map-function like this

  public function map($tabula): array
    {   
        //unformatieren
        $soll =  $tabula->soll;
        //vom string Randwerte abschneiden: [ und ]
        $soll = substr($soll, 1, -1);
        // in Array umwandeln
        $soll = explode( ',', $soll);
        //das gleiche mit soll
        $haben =  $tabula->haben;
        $haben = substr($haben, 1, -1);
        $haben = explode( ',', $haben);
        // als ersten Wert den Header soll/haben einfügen ins Array
        array_unshift($haben, "haben");
        array_unshift($soll, "soll");

        return [
            $soll, 
            $haben
        ];
    }

So now it works, thanks! Each array covers a row in excel now.

  • Related