pmiranda
pmiranda

Reputation: 8450

export large data with chunk in Laravel-Excel

With this code I can export to excel the data of MyModel, works ok:

Excel::create('Filename', function ($excel) {
                $excel->sheet('Contratos', function ($sheet) {
                    $datos = MyModel::select([
                        'id', 'data'])
                        ->get();
                    $sheet->fromArray($datos, null, 'A1', false, false);
                });
            })->export('xls');

But I need to chunk the data to generate the excel, because in another model I have too much data (like 9000 records). I was seein some examples like this one:

http://www.thecreativeroad.com/blog/export-large-dataset-using-laravel-excel-using-laravel-db-chunk

$data = $user->query();
    try{
        return Excel::create('FileName', function($excel) use($data){

        $data->chunk(100, function ($users) use($excel) {
            $collection = $this->transformCollection($users);

            $excel->sheet('OrgSubUserList', function($sheet) use($collection){
                $sheet->fromModel($collection, null, 'A1', true);
            });
        });

        })->export('xls');
    }
    catch(Exception $e)
    {
        return false;
    }

But I can't figure how to apply it to my code, I have a confusion between the order on the sheets and the file itself. Any hint?

Upvotes: 2

Views: 11296

Answers (1)

vipinlalrv
vipinlalrv

Reputation: 3075

pass false as third parameter to chunk() to disable queuing

$data = [];
Excel::filter('chunk')->load($path)->chunk(1000, function ($results) use (&$data) {
    foreach ($results as $row) {
        $data[] = $row;
    }
}, $shouldQueue = false);
return $data;

Upvotes: 0

Related Questions