These are chat archives for PHPOffice/PHPExcel

20th
Apr 2017
Adrien Crivelli
@PowerKiKi
Apr 20 2017 03:48

@anuluvi you could try something like the following:

A view helper to send Excel files:

<?php

namespace Application\View\Helper;

use PHPExcel;
use PHPExcel_Writer_Excel2007;
use PHPExcel_Writer_HTML;
use Zend_View_Helper_Abstract;

/**
 * Send the excel document to the client as attached file
 */
class SendExcel extends Zend_View_Helper_Abstract
{
    /**
     * Send the excel document to the client as attached file
     * @param PHPExcel $workbook the workbook to send
     * @param string $filename the filename suggested to save as for the end-user
     * @param bool $debug if true, will output (approximative) HTML for easier debugging
     */
    public function sendExcel(PHPExcel $workbook, string $filename = 'output.xlsx', bool $debug = false): void
    {
        $workbook->setActiveSheetIndex(0);

        // Set common properties
        $workbook->getProperties()->setCreator(_tr('My application'));
        $workbook->getProperties()->setLastModifiedBy(_tr('My application'));
        $workbook->getProperties()->setTitle($filename);
        $workbook->getProperties()->setSubject($filename);

        if ($debug) {
            $objWriter = new PHPExcel_Writer_HTML($workbook);
        } else {
            $objWriter = new PHPExcel_Writer_Excel2007($workbook);

            // Save Excel 2007 file
            header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header("Content-Disposition: attachment; filename=\"$filename\"");
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0,pre-check=0');
            header('Pragma: public');
        }
        $objWriter->setPreCalculateFormulas(false);
        $objWriter->save('php://output');
    }
}

A view.phtml using that helper:

<?php

// Create new PHPExcel object
$workbook = new PHPExcel();
$this->workbook = $workbook;

// Add some data
$workbook->getActiveSheet()->getCell('A1')->setValue('Hello World');

$filename = 'foo.xlsx';
$this->sendExcel($workbook, $filename);