下载 PhpSpreadsheet 文件之前不保存

Download PhpSpreadsheet file without save it before

我正在使用 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
);

但是我不想保存文件然后再读给return给用户。我想直接下载 Excel 内容。有办法吗?

我搜索了如何生成内容流(如 所说),但没有成功。

提前致谢,抱歉我的英语不好

据我了解,您正在代码中生成内容。 你可以 stream the response in Symfony and configure PhpSpreadsheet Writer to save to 'php://output' (see here the official doc 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;
    }
}

这是 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 它回到控制器中

return $response;