Skip to content

Instantly share code, notes, and snippets.

@floriankapaun
Forked from ZhukV/ExcelFileResponse.php
Last active October 26, 2022 13:04
Show Gist options
  • Save floriankapaun/a2718f0cf1bd4f6bd27d5fd348efbfc8 to your computer and use it in GitHub Desktop.
Save floriankapaun/a2718f0cf1bd4f6bd27d5fd348efbfc8 to your computer and use it in GitHub Desktop.
.xlsx file response to download Excel file generated by PHPSpreadsheet (Symfony HttpFoundation)
<?php
declare(strict_types=1);
namespace App\HttpFoundation;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\Response;
/**
* XlsxResponse represents an .xlsx file response.
*/
class XlsxResponse extends Response
{
private string $excelContent;
public function __construct(Xlsx $writer, string $fileName)
{
ob_start();
$writer->save('php://output');
$this->excelContent = ob_get_contents();
ob_end_clean();
parent::__construct(
null,
200,
[
'Content-Disposition' => "attachment; filename=\"{$fileName}\"",
'Content-Type' => 'application/octet-stream; charset=utf-8'
]
);
}
/**
* {@inheritDoc}
*/
public function sendContent(): static
{
echo $this->excelContent;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment