将大量数据导出到xlsx

时间:2017-08-03 19:47:52

标签: php laravel laravel-5 phpexcel laravel-excel

我需要将带有MYISAM引擎的MySQL数据库表中的大数据集导出到Laravel中的.xlsx文件中。

我正在使用基于maatwebsite/laravel-excelPHPExcel包。

数据库包含大约500,000行,93列(大约46,500,000个单元格),以及关于标题结构的大量计算。

这是我目前正在使用的代码:

// $excel_data contains some data regarding the project, nothing relevant here
$output = Excel::create('myproject-' . $excel_data->project->name . '-'.date('Y-m-d H:i:s') . '-export', function($excel) use($excel_data) {

        // Set the title
        $excel->setTitle($excel_data->project->name . ' Export');

        $excel->sheet('Data', function($sheet) use($excel_data) {

            $rowPointer = 1;

            $query = DB::table('task_metas')
                ->where([
                    ['project_id', '=', $excel_data->project->id],
                    ['deleted_at', '=', null]
                ])
                ->orderBy('id');

            $totalRecords = $query->count();
            // my server can't handle a request that returns more than 20k rows so I am chunking the results in batches of 15000 to be on the safe side
            $query->chunk(15000, function($taskmetas) use($sheet, &$rowPointer, $totalRecords) {
                // Iterate over taskmetas
                foreach ($taskmetas as $taskmeta) {
                    // other columns and header structure omitted for clarity
                    $sheet->setCellValue('A' . $rowPointer, $rowPointer);
                    $sheet->setCellValue('B' . $rowPointer, $taskmeta->id);
                    $sheet->setCellValue('C' . $rowPointer, $taskmeta->url);

                    // Move on to the next row
                    $rowPointer++;
                }
                // logging the progress of the export
                activity()
                    ->log("wrote taskmeta to row " . $rowPointer . "/" . $totalRecords);

                unset($taskmetas);
            });
        });

    });

    $output->download('xlsx');

根据日志,行已成功写入文件,但文件创建本身需要很长时间。事实上,它在1小时内没有完成(这是该函数的最大执行时间)。

将它导出到csv效果很好,大约10分钟就可以编译文件&下载它,但我无法使用 - 输出文件需要xlsx

我该怎么做才能加快文件创建过程?只要我能达到相同的效果,我也会接受其他选择。

1 个答案:

答案 0 :(得分:0)

我有3条建议:

  1. 使用cursor(虽然直到今天,我还没有发现它是否比块更好 - 也许你的情况可能会验证这一点) - 真诚地我只使用了这个和它的Eloquent。

  2. 减小块的大小。我认为在内存中加载15000条记录已经成为一个问题。

  3. 首先创建excel文件,然后在工作表上使用rows()方法追加多行。 (这可能不会很好,因为它需要一个数组)

相关问题