使用angular 5 HttpClient请求下载Excel文件

时间:2018-09-06 05:01:49

标签: angular

我正在尝试使用角度5(httpClient请求)下载Excel文件。我正在使用的功能是:

getWithAttachement(url: string, filename: string) {

const httpOption: Object  = {
  observe:  'response',
  headers: new HttpHeaders({
    'Content-Type' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),
  responseType: 'Blob'
};

return this.http.get(url, httpOption)
.map(res => {
  return {
    filename: filename,
    data: new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
  };
})
.subscribe(res => {
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveBlob(res.data, res.filename);
  } else {
    const link = window.URL.createObjectURL(res.data);
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.href = link;
    a.download = res.filename;
    a.click();
    window.URL.revokeObjectURL(link);
    a.remove();
  }
}, error => {
  console.log('download error:', JSON.stringify(error));
}, () => {
  console.log('Completed file download.');

});
  }

我能够下载文件,但是无法读取其内容。错误是:

Microsoft Excel Excel无法打开文件“ SchedulingReport.xlsx”,因为文件格式或文件扩展名无效。验证文件未损坏,并且文件扩展名与文件格式匹配。好

0 个答案:

没有答案