Symfony 1.4 and sfPHPExcelPlugin


Symfony 1.4 and sfPHPExcelPlugin

我正在为Symfony 1.4使用PHPExcel插件(sfPHPExcelPlugin)。当我制作Excel文件时,它被下载到用户的电脑上,而不是被写入服务器?

您可以使用特殊的头强制下载文件

if (file_exists($this->temp_XLSX))
      {
        $content = file_get_contents($this->temp_XLSX);
        unlink($this->temp_XLSX);
        unlink($this->temp_CSV_file);
        header('Content-type: application/force-download');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        echo $content;
        die;
      }

首先,我不认为使用插件是必要的。没有它,你可以做得很好,只需将PHPExcel直接导入到你的项目中。

据我记忆所及,在内存中没有用PHPExcel生成Excel文件并将内容发送到任何地方的选项。我一直在做的是将Excel文件保存到tmp文件,读取文件的内容,将其发送给用户并删除tmp文件。类似这样的东西(内部行动):

 $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
 $tmpName = md5(date('dmYHis'));
 $tmpFile = sfConfig::get('sf_web_dir').'/tmp/'.$tmpName;
 $objWriter->save($tmpFile);
 $fileSize = filesize($tmpFile);
 $fileContents = file_get_contents($tmpFile);
 unlink($tmpFile);
 $this->getResponse()->clearHttpHeaders();
 $this->getResponse()->setStatusCode(200);
 $this->getResponse()->setContentType('application/vnd.ms-excel');
 $this->getResponse()->setHttpHeader(
     'Content-Disposition', 
     'attachment; filename=worksheet.xls'
 );
 $this->getResponse()->setHttpHeader('Content-Transfer-Encoding', 'binary');
 $this->getResponse()->setHttpHeader('Content-Length', $fileSize);
 return $this->renderText($fileContents);