Angular 4下载xls [复制]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我正在尝试使用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();
  });
}

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

php excel angular
2个回答
0
投票

如果不需要订阅,那么只需在服务中的downloadTemplate()方法中使用它

  window.location.href = your_URL;

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对象返回给用户。就这样。

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