【问题标题】:export large data with chunk in Laravel-Excel在 Laravel-Excel 中用块导出大数据
【发布时间】:2018-04-15 03:51:03
【问题描述】:

使用此代码,我可以将 MyModel 的数据导出到 Excel,工作正常:

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');

但我需要对数据进行分块以生成 Excel,因为在另一个模型中我有太多数据(如 9000 条记录)。我在一些这样的例子中看到过:

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;
    }

但我不知道如何将它应用到我的代码中,我对工作表上的顺序和文件本身之间存在混淆。有什么提示吗?

【问题讨论】:

  • 另外,来自查询构建器方法的数据返回数组,例如DB::select()
  • 工作表会单调递增,数据的顺序也是一样的,这取决于你的数据是如何排序的。

标签: laravel chunks laravel-excel


【解决方案1】:

将 false 作为第三个参数传递给 chunk() 以禁用排队

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

【讨论】:

    猜你喜欢
    • 2019-09-21
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2020-10-11
    • 2021-12-23
    • 2016-06-30
    相关资源
    最近更新 更多