下载PhpSpreadsheet文件而不保存之前 [英] Download PhpSpreadsheet file without save it before
问题描述
我正在使用 PhpSpreadsheet 在Symfony 4中生成Excel文件.我的代码是:>
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
);
但是我不想保存文件,然后阅读以返回给用户.我想直接下载Excel内容.有办法吗?
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.
在此先感谢我的英语
推荐答案
据我了解,您正在代码中生成内容. 您可以在Symfony中流式传输响应并配置PhpSpreadsheet Writer保存到'php://output'(请参阅此处的官方文档
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).
这是一个使用Symfony 4.1和Phpspreadsheet 1.3的工作示例:
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;
}
}
这篇关于下载PhpSpreadsheet文件而不保存之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!