U
U
ukoHka2017-10-26 14:31:28
Yii
ukoHka, 2017-10-26 14:31:28

How to properly export PhpExcel to Yii2?

There is a link to the table/export action. Clicking on the link opens a new page with the current layout and thumbnails in the place where the content of the view is normally displayed. When the page is refreshed, the required file is downloaded. In the actionExport() action, the code for creating an xlsx file is written, ending with and a new layout is specified
<a href="/table/export">export</a>
$objWriter->save('php://output');

<?php
echo $content;

How can I make it so that when I click on a link, the file is downloaded immediately?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mykola, 2017-10-26
@iSensetivity

/**
     * @param $objPHPExcel
     * @param string $filename
     */
    protected static function downloadExcel($objPHPExcel, $filename = 'file')
    {
        $filename = $filename . '.csv';
        // Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');

        return $objWriter->save('php://output');
    }

Something like this in the controller:
return static::downloadExcel($objPHPExcel, 'the-file');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question