如何从Angular7中的PHPExcel下载Excel文件而不将其保存在服务器上?

时间:2019-05-09 12:17:28

标签: excel download phpexcel angular7

我正在使用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。像这样:

enter image description here

但是当订阅运行时,控制台中出现以下错误:

  

错误:语法错误:意外的令牌-XMLHttpRequest.onLoad中JSON.parse()位置JSON中的位置0

我想知道为什么当我单击使订阅运行的按钮时为什么未下载文件,以及如何使它生效。

1 个答案:

答案 0 :(得分:0)

我在这里找到了解决问题的方法:Make Angular expect other response than JSON

我要解决的问题是更改服务以使其期望除JSON之外的其他响应:

 var HTTPOptions = {
      headers: new HttpHeaders({
        'Accept': 'text/html, application/xhtml+xml, */*',
        'Content-Type': 'application/x-www-form-urlencoded'
      }),
      'responseType': 'blob' as 'json'
   }
    return this.http.post<any[]>(url, body, HTTPOptions);