如何使用File Saver在Angular中下载Excel文件

问题描述 投票:1回答:1

我已经在PHP中创建了发布表单,单击该按钮便下载了一个excel文件,并且我还将一些表单数据发布到了URL和用于通过纯HTML成功下载并提交表单的文件中。

在PHP中,这是将表单发布到文件时触发的函数

public function downloadExcel($fileName = '', $addTimeStamp = true) {
    $fileName = (!$fileName) ? 'excel_download' : preg_replace('/\s+/', '_', $fileName);
    if ($addTimeStamp) {
        $fileName .= date('_d_m_Y_H_i_s');
    }
    $fileName .= '.xlsx';
    $this->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $fileName . '"');
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: cache, must-revalidate');
    header('Pragma: public');
    $objWriter = PHPExcel_IOFactory::createWriter($this, 'Excel2007');
    $objWriter->save('php://output');
}

[工作时,我在请求标题中设置了以下内容

enter image description here

并且在响应中没有任何显示

enter image description here

但是现在我们试图将前端迁移到我们可以从中下载文件的Angular框架,我已经尝试了他的方式

downloadTheExport() {
  this.downloadfile().subscribe((blob: any) => {
    const blobdownload = new Blob([blob], { type: "application/vnd.ms-excel;charset=utf-8" });
    saveAs(blobdownload, 'testdata.xls');
  });
}

downloadfile(){
  const formDataForExport: FormData = new FormData();
  formDataForExport.append('export', 'ALL');

  return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
    headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' }
  });
}

并且当我尝试在Angular中下载此文件时,我发现当在Angular中进行调用时,Content-Type的请求标头似乎已更改为Content-Type: multipart/form-data; boundary angular,而且当我在响应选项卡中看到它显示一些数据时,如下。

enter image description here在这种情况下,能否请您帮助我如何在Angular中实现下载

php angular download phpexcel
1个回答
1
投票

对于您的[[Request header]]中的Content-Type是正确的,因为您确实通过php后端发布了一个formDataForExport。

© www.soinside.com 2019 - 2024. All rights reserved.