从 class 下载 PHPExcel 文件

Download PHPExcel File From a class

我尝试从 php class 下载 excel 文件。我的代码:

use Api\Tasks\Task;
use PHPExcel;
use PHPExcel_IOFactory;

class GetReportByID extends Task {

    private $reportID;

    function __construct($reportID)
    {
    $this->reportID=$reportID;
    parent::__construct();
}

/**
 * Start of Task
 */
public function start()
{
    $this->createReport();
}

private function createReport()
{
    switch ($this->reportID) {
        case '1':
            $this->test();
            break;
    }
}

private function test()
{
    $excel = new PHPExcel();
    // We'll be outputting an excel file
    header('Content-type: application/vnd.ms-excel');
    // It will be called file.xls
    header('Content-Disposition: attachment; filename="file.xls"');
    // Write file to the browser
    // Do your stuff here
    $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
    // This line will force the file to download
    $writer->save('php://output');

}
}

使用调试我可以看到 class 已正确加载。但文件并未开始下载。 当我使用简单的脚本时,它工作正常。 是否可以从 php class 创建下载文件?

找到解决方案,不得不使用 Blob 来获取输出。 此外,重要使用

responseType: "arraybuffer",

这是最终代码。

客户端部分:

$scope.reports = function (reportID) {
    $http({
        method: 'GET',
        url: "api/registration/reports/"+reportID,
        // This is important! Tell it to expect an arraybuffer
        responseType: "arraybuffer",
    }).
    success(function(data) {
        var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "data.xls";
        document.body.appendChild(a);
        a.click();
    });
};

和服务器部分:

   private function test()
{
    $objPHPExcel = new PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', 'Hello')
        ->setCellValue('B2', 'world!')
        ->setCellValue('C1', 'Hello')
        ->setCellValue('D2', 'world!');

    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="01simple.xlsx"');
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');
}

请注意,我还更改了此处的 Headers 和 Excel 版本。没有使用以前的设置对其进行测试,但这是一个有效的示例。