我正在使用PhpSpreadsheet在Symfony 4中生成一个Excel文件。我的代码是:
$spreadsheet = $this->generateExcel($content);
$writer = new Xlsx($spreadsheet);
$filename = "myFile.xlsx";
$writer->save($filename); // LINE I WANT TO AVOID
$response = new BinaryFileResponse($filename);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
但是我不想保存文件,然后再阅读以返回给用户。我想直接下载Excel内容。有办法吗?
我已经搜索了如何生成内容流(如this answer所述),但没有成功。
在此先感谢我的英语
答案 0 :(得分:9)
据我了解,您正在代码中生成内容。 您可以stream the response in Symfony并将PhpSpreadsheet Writer配置为保存到'php:// output'(请参见此处的官方文档Redirect output to a client's web browser)。
这是一个使用Symfony 4.1和Phpspreadsheet 1.3的工作示例:
<?php
namespace App\Controller;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use PhpOffice\PhpSpreadsheet\Writer as Writer;
class TestController extends Controller
{
/**
* @Route("/save")
*/
public function index()
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Writer\Xls($spreadsheet);
$response = new StreamedResponse(
function () use ($writer) {
$writer->save('php://output');
}
);
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', 'attachment;filename="ExportScan.xls"');
$response->headers->set('Cache-Control','max-age=0');
return $response;
}
}
答案 1 :(得分:1)
这是 Laravel 的解决方案。但它最终仍然使用 Symfony\Component\HttpFoundation\StreamedResponse
。
$contentDisposition = 'attachment; filename="' . $fileName . '"';
$contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
$response = response()->streamDownload(function () use ($spreadsheet) {
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', $contentType);
$response->headers->set('Content-Disposition', $contentDisposition);
然后您可以使用
直接将响应作为流发送$response->send();
或者只是将其返回到控制器中
return $response;