【发布时间】:2019-05-09 12:17:28
【问题描述】:
我正在使用 Codeigniter 和 PHPExcel 来生成 .xls 文件。当我尝试将其保存在服务器上时一切正常,但我不想将其保存在服务器上,我想在 Angular 7 收到带有 blob 的响应时下载它。
我的 PHP Api 是这样的:
function getFile:
$this->objPHPExcel->getProperties()->setCreator("My File")->setLastModifiedBy("My File");
$this->objPHPExcel->getProperties()->setCreator("My File")->setTitle("");
$this->objPHPExcel->getProperties()->setCreator("My File")->setSubject("");
$this->objPHPExcel->getProperties()->setCreator("My File")->setDescription("");
$this->objPHPExcel->getProperties()->setCreator("My File")->setKeywords("");
Here I have a foreach creating the rows and cols:
$this->objPHPExcel->setActiveSheetIndex(0);
$this->objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
$this->objPHPExcel->getActiveSheet()->setCellValue( $col.$linha , $val);
$this->objPHPExcel->getActiveSheet()->getStyle( $col.$linha )->getFont()->setBold( true );
$this->objPHPExcel->getActiveSheet()->getStyle( $col.$linha )->applyFromArray($centerStyle);
After foreach:
$objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel5');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
Obs: If I set a path to the file it is created without problems:
$objWriter->save($filePath.'test.xls');
我的 Angular 7 服务是这样的:
generateExcel(body){
const url = `${baseurl.base_url}api/generate_excel/get_file`;
const header = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any[]>(url, body, {headers: header});
}
而我在 Component 中的订阅是这样的:
this.generateExcelService.generateExcel(JSON.stringify(table)).subscribe((response: any) => {
let blob = new Blob([response], {type: 'application/vnd.ms-excel'})
saveAs(blob, 'file.xls')
})
我猜响应是 Blob。像这样的:
但是当订阅运行时,我在控制台中收到以下错误:
错误:SyntaxError: Unexpected token � in JSON at JSON.parse () at XMLHttpRequest.onLoad 的位置 0
我想知道为什么当我单击使订阅运行的按钮时没有下载文件以及我必须做些什么才能使其正常工作。
【问题讨论】:
标签: excel download phpexcel angular7