Skip to content

Instantly share code, notes, and snippets.

@damijanc
Created September 13, 2018 11:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save damijanc/c23d7358d298898c96d4d7b5eec0d616 to your computer and use it in GitHub Desktop.
Save damijanc/c23d7358d298898c96d4d7b5eec0d616 to your computer and use it in GitHub Desktop.
Example on how to download an Excel file created with PhpSpreadsheet
<?php
$streamedResponse = new StreamedResponse();
$streamedResponse->setCallback(function () {
$spreadsheet = //create you spreadsheet here;
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
});
$streamedResponse->setStatusCode(Response::HTTP_OK);
$streamedResponse->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$streamedResponse->headers->set('Content-Disposition', 'attachment; filename="your_file.xlsx"');
return $streamedResponse->send();`
@andykillen
Copy link

this really need to have the use statements on this, otherwise its not a solution, only further problems that need to be worked out

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Response;

@damijanc
Copy link
Author

It was an excerpt from the code, but thank you for pointing it out. I hope that no one will just blindly copy and paste it.

@timotheemoulin
Copy link

Any way to use id "standalone" without the Symfony components?

@timo002
Copy link

timo002 commented Jan 30, 2020

@timo

Any way to use id "standalone" without the Symfony components?

<?php

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="GeneratedFile.xlsx"');
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');

@damijanc
Copy link
Author

@timo

Any way to use id "standalone" without the Symfony components?

<?php

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="GeneratedFile.xlsx"');
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');

I would add fastcgi_finish_request(); at the end:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment