簡體   English   中英

保存 PHPSpreadSheet 對象

[英]Saving a PHPSpreadSheet Object

我有一個 Laravel 應用程序部署到 Google App Engine。 根據 GAE 的架構規則,您不能將文件保存到本地路徑。 我正在使用PHP 電子表格生成 Xlsx 文件並為用戶下載它們。 所以這在本地有效,但在部署的應用程序中無效。

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save('storage/SomeExcelFile.xlsx');

然后我可以用..下載文件

return Storage::disk('public')->download('SomeExcelFile.xlsx');

但是無法在應用程序的生產版本上本地保存文件,我將如何存儲我的文件? 我將我的應用程序連接到可以上傳文件的存儲桶。 但是我需要文件路徑來執行此操作,並且由於該文件是在應用程序中以腳本方式創建的,並且在部署之前從未存儲過,因此我找不到存儲它的方法。

據我發現,您不能將 xlsx 文件直接寫入磁盤。 例如,我可以將帶有文本sample data的文本文件寫入我的谷歌雲存儲桶..

Storage::disk('gcs')->put('String.txt', 'sample data');

但是找不到使用我的excel文件的方法。 此外,應用程序部署在 Flex 環境中,因此我無法使用文件 url 結構gs://

找到了一個使用Symfony流式傳輸文件的工作

$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="Services Reformatted.xlsx"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;

試試這種方式:

file_put_contents(public_path('filename.xlsx'), $writer);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM