如何在使用 Phpspreadsheet 下载之前修改 excel?

How to modify an excel before downloading it with Phpspreadsheet?

我正在尝试使用 php://output 保存 excel,但我想在下载之前对其进行修改。我试过了,但显然不起作用。

            $writer = new Xlsx($spreadsheet);
            $response = new StreamedResponse(
            static function () use ($writer) {
                $file = $writer->save('php://output');

                //$zip = new \ZipArchive();
                //if ($zip->open('php://output') === TRUE) {
                //   <do something>
                //}
            },
        );

    $response->headers->set('Content-Type', 'application/vnd.ms-excel');
    $response->headers->set('Content-Disposition', 'attachment; 
    filename=<file.xlsx>');
    $response->headers->set('Cache-Control', 'max-age=0');

    return $response;

我会把它分成 3 个步骤

1) 将电子表格写入文件

$filename = "filename.xlsx";
$writer = new Xlsx($spreadsheet);
$writer->save($file);

2) 加载文件(作为 zip 存档)更改它并保存更改后的文件

$zip= new \ZipArchive;
if ($zip->open($filename) === TRUE) {
    //load a file from the xlsx (zip)
    $xmlContentOld = $zip->getFromName("whatever.xml");
    $xmlContentNew = $xmlContentOld . "<addedTag></addedTag>";
    //Delete the old file and write the file with new content into the archive
    $zip->deleteName("whatever.xml")
    $zip->addFromString("whatever.xml", $xmlContentNew );
    //close and update zip
    $zip->close();
}

3) 将更改后的存档文件提供给浏览器

$fp = fopen($filename, 'rb');

// send the right headers
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Length: " . filesize($filename));

fpassthru($fp);