用Phpspreadsheet下载Excel之前如何修改它?

时间:2019-11-15 20:31:49

标签: php excel 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;

1 个答案:

答案 0 :(得分:0)

我将其分为三个步骤

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);
相关问题