如何在Angular 8中下载Excel文件作为API响应

问题描述:

我有一个API,该API返回excel文档作为响应.该请求将是一个简单的json.

I've an API which returns an excel document as response. The request will be one simple json.

我搜索了google并找到了一些代码库来下载文件,并在应用程序中使用了它,但是遇到一些错误,无法找到解决方案.下面是我的代码库.

I've searched google and found some code base to download the file and I've used it in my application, but I'm getting some errors and unable to find it out the solution. Below are my code base.

component.ts

import rxjs/Rx;

details = {id: 75,name: "some name"}

this.nameService.getData(this.details).subscribe(response => {
this.downloadFile(response);
})

downloadFile(data: Response) {
  const blob = new Blob([data], { type: '.xlsx' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}

nameService.ts

getData(postData) {
  return this.httpService.post('https://localhost:8080/getFile/', postData);
}

httpService.ts

constructor(private http: HttpClient)
post(apiEndpoint: string, request: any) :Observable<any> {
 return this.http.post<any>(apiEndpoint,request);
}

使用上述代码库,我遇到以下两个错误,并且文件未下载.

with the above code base I'm getting below two errors and the file is not downloaded.

  1. 获取错误:

类型响应不可分配给类型Blobpart".创建Blob(const blob = new Blob([data],{type:'.xlsx'});)

"Type Response is not assignable to type Blobpart" in creating the Blob(const blob = new Blob([data], { type: '.xlsx' });)

  1. 如果我将数据更改为任何(downloadFile(data:any)),则上述错误(1)将消失,但我收到的 httperror 响应为语法错误: json.parse
  2. 位置0处的json中意外的令牌P
  1. If I change the data as any (downloadFile(data: any)) the above error(1) will go but I'm getting an httperror response as 'Syntax error: unexpected token P in json at position 0 at json.parse

如果有人找到上述问题的解决方案,请提供帮助.

Kindly help if anyone finds any solution to the above issues.

  1. 您需要在请求中设置响应标题 {responseType:'blob'} .

在创建blob文件时,您需要传递正确的MIME类型.(例如 application/octet-stream application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ).

You need to pass in the correct MIME-Type as you'are creating the blob-file. (f.e. application/octet-stream or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet).

component.ts

component.ts

downloadFile(data: Response) {
  const blob = new Blob([data], { type: 'application/octet-stream' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}