Download PhpSpreadsheet file without save it before

家住魔仙堡 提交于 2019-12-10 03:21:12

问题


I'm using PhpSpreadsheet to generate an Excel file in Symfony 4. My code is:

$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
);

But I don't want to save the file and then read it to return to the user. I would like to download Excel content directly. Is there a way to do It?

I've searched how to generate a stream of the content (as this answer says) but I hadn't success.

Thanks in advance and sorry about my English


回答1:


As I understand you are generating the content in your code. You can 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).

Here is an working example using Symfony 4.1 and 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;
    }
}


来源:https://stackoverflow.com/questions/50993968/download-phpspreadsheet-file-without-save-it-before

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!