PhpSpreadsheet return file instead of saving it

Use php://output

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
$writer->save("php://output");

call ob_end_clean(); just before the $writer->save('php://output').

ob_end_clean();
$writer->save('php://output');


You could send the file directly after its creation, instead of the redirect to the file.

$filename = 'hello world.xlsx';
$writer->save($filename);

// Set the content-type:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($filename));
readfile($filename); // send file
unlink($filename); // delete file
exit;