Angular 4下载xls

时间:2018-01-22 08:41:57

标签: php excel angular

我正在尝试使用angular和php为后端下载excel文件(.xls)

我的后端已经发送了我的excel文件作为回复,当我检查它时,它以正确的格式返回

但是我的角度4将文件作为损坏的格式返回(它包含一些符号,如��ࡱ�;��

下面是我的角度代码:

服务

private headers = new Headers({
 'Content-Type': 'application/x-www-form-urlencoded'
});

downloadTemplate() {
  this.options = new RequestOptions();
  this.options.headers = this.headers;

  const params: URLSearchParams = new URLSearchParams();
  params.set('token', this.currentUser.token);
  this.options.search = params;

  return this.http.get(environment.api_host + '/template', this.options);
}

组件

template() {
  this._apiService.downloadTemplate().subscribe((response) => {
    const blob = new Blob([(<any>response)._body], {type: 'application/vnd.ms-excel'});
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'template.xls';
    document.body.appendChild(link);
    link.click();
  });
}

从我的代码中,有什么我想念的吗?

2 个答案:

答案 0 :(得分:0)

如果不需要订阅,请在服务中使用downloadTemplate()方法

  window.location.href = your_URL;

答案 1 :(得分:0)

我正在使用FileSaver库来处理Angular应用程序中的文件:http://alferov.github.io/angular-file-saver/

这里有示例代码:

getTemplate(): Observable<Blob> {
    this.apiService.http()
        .get(environment.api_host + '/template', { responseType: ResponseContentType.Blob })
        .map(r => r.blob())
        .subscribe(
            template => {
                FileSaver.saveAs(new Blob([template]), "template.xml");
            },
            error => {
                console.error(error);
            }
        );
}

重要的是,您应该将标头Content-Type: application/octet-stream添加到PHP响应中。完整且有效的标题集:

$file = fopen("/tmp/examplefile.xls", "r");

array(
    'Content-Disposition' => 'attachment; filename="' . basename($filePath) . '"',
    'Content-Type' => 'application/octet-stream',
    'Content-Length' => filesize($filePath),
    'Expires' => '@0',
    'Cache-Control' => 'must-revalidate',
    'Pragma' => 'public'
);

我认为代码中的问题是标头定义:const blob = new Blob([(<any>response)._body], {type: 'application/vnd.ms-excel'});或http客户端选项中的响应类型。您应该从PHP发送'octet / stream'(二进制数据)。在angular中根据此数据创建Blob对象并将Blob对象返回给用户。就是这样。

相关问题