Question

I'm using the PHPExcel plugin (sfPHPExcelPlugin) for Symfony 1.4. As I make the Excel file is downloaded to the user's PC, instead of being written to the server?

Was it helpful?

Solution 2

First of all I don't think using the plugin is necessary. You can do very well without it, just importing the PHPExcel directly to your project.

As far as I remember there is no option to generate an Excel file with PHPExcel in memory and send the content anywhere. What I'm always doing is saving the Excel file to tmp file, read content of the file, send it to the user and delete the tmp file. Something like this (inside action):

 $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);

OTHER TIPS

You can use special headers to force downloading the file

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;
      }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top