Search code examples
laravel-5maatwebsite-excel

how to set the columns in an excel using Maatwebsite using laravel 5.4


Hi i have this download csv. Now my problem is i want to get the certain columns for my excel file not all fields from the database to be pulled to csv. Now my download csv works good and could download the data. Now i want that only certain columns to be displayed into my csv file. the getCell code wont work. This is my code below

//download csv all pending
    public function downloadExcelAllPending($type){
        $data = BookingHistory::orderBy('checkin_date', 'desc')->get()->toArray();

        return Excel::create('booking_history', function($excel) use ($data) {

        $excel->sheet('mySheet', function($sheet) use ($data)
        {

            $sheet->getCell('A1')->setValue('first_name');
            $sheet->fromArray($data);


         });

        })->download($type);

Now this line of code here $sheet->getCell('A1')->setValue('first_name'); won't work. Can someone help me figured this thing out?. Any help is muchly appreciated. TIA.


Solution

  • You could select only the desired attributes when fetching the data from the database:

    public function downloadExcelAllPending($type)
    {
        $data = BookingHistory::orderBy('checkin_date', 'desc')
            ->select([
                'checkin_date',
                // your other attributes
            ])
            ->get()
            ->toArray();
    
        return Excel::create('booking_history', function ($excel) use ($data) {
            $excel->sheet('mySheet', function ($sheet) use ($data) {
                $sheet->fromArray($data);
            });
        })->download($type);
    }