Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

Impossible to export large amount of data using: Spatie\SimpleExcel

Hello

I try to export a Sql query to excel file , but when the number of rows is bigger than 200k I get no results :

This page isn’t workinglocalhost didn’t send any data.
ERR_EMPTY_RESPONSE

This is my code :

        $writer = SimpleExcelWriter::streamDownload('your-export.xlsx');
        $starttimer = microtime(true);
        $i = 0;

        $this->sqlQuery('2022-05-01', '2022-12-15')->lazy() // a function returning the collection result  
            ->each(function ($row) use (&$i, $writer) {
                $i++;
                $writer->addRow([
                    'date' => $row->date,
                    'user_name' => $row->user_name,
                ]);
                if ($i % 100 === 0) {
                    flush(); // Flush the buffer every 1000 rows
                }
            });

         $writer->toBrowser();

So as I said it works for low amount of data but if it's more than 200K!

any idea ?

0 likes
5 replies
GodziLaravel's avatar

@Tray2 thanks, I think this is the solution because I tried many packages and it seems not supporting large data

GodziLaravel's avatar

@tray2

I made an example :

$headers = [
    'Content-type' => 'application/vnd.ms-excel',
    'Content-Disposition' => 'attachment; filename=users.xls',
];

// Create the XLS file using PHP's built-in functions
$output = fopen('php://output', 'w');
fputcsv($output, ['ID', 'Name', 'Email']);

// Use chunking to retrieve and process the data in smaller batches
DB::table('users')->select('id', 'name', 'email')->orderBy('id')->chunk(1000, function ($results) use ($output) {
    foreach ($results as $row) {
        fputcsv($output, [$row->id, $row->name, $row->email]);
    }
});

fclose($output);

// Create a Response instance with the file's content and headers
$response = new Response(file_get_contents('php://output'), 200, $headers);

// Return the response to make the file downloadable
return $response;

but it's not downloading ! it's just displaying the result on the browser ! any idea?

Please or to participate in this conversation.