我尝试从php类下载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');
}
}
使用debug我可以看到该类已正确加载。但该文件没有开始下载。 当我使用简单的脚本时,它的工作正常。 是否可以从php类创建下载文件?
答案 0 :(得分:1)
想出解决方案,必须使用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');
}
注意我也在这里更改了标题和Excel版本。没有使用以前的设置测试它,但这是一个有效的例子。