簡體   English   中英

用phpexcel保存到臨時文件

[英]Save with phpexcel to temporary file

我必須將Excel保存在一個臨時文件中,但我不知道如何

本來這樣我保留Excel文件

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Autolarte.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); 
header ('Cache-Control: cache, must-revalidate'); 
header ('Pragma: public'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

現在我想要的是使用該Excel文件的內容創建一個臨時文件

我有這個例子,但是由於我不知道我的excel的內容是什么變量,因此在我的例子中沒有實現

$temp = tmpfile();
fwrite($temp, "writing in the temporary file");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp);

現在是我需要的臨時文件,我想在addfile中放入臨時文件的路徑和名稱,以將excel添加到zip文件中

$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$zip->addFile('/path/to/index.txt', 'newname.txt');
$zip->addFromString("testfilephp.txt", "#1 This is a test string added as  testfilephp.txt.\n");
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
exit;

save()命令保存到文件,但是您現在使用php://output作為文件名來獲得直接輸出。 只是改變它。

$tempfile = tempnam();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($tempfile);

之后不要忘記使用unlink()刪除文件。

   //create a dir temporal
        $tmpHandle = tmpfile();
        $metaDatas = stream_get_meta_data($tmpHandle);
        $tmpFilename = $metaDatas['uri'];
   //create a object tu save de excel file
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
   //save the excel in a temporaly dir
        $objWriter->save($tmpFilename);
   //create the zip
        $zipname = 'file.zip';
        $zip = new ZipArchive;
        $zip->open($zipname, ZipArchive::CREATE);
        $zip->addFile($tmpFilename, 'newname.xlsx');
        $zip->close();
        unlink($tmpFilename);
        fclose($tmpHandle);
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename='.$zipname);
        header('Content-Length: ' . filesize($zipname));
        readfile($zipname);
        exit;

暫無
暫無

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

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