我是Angular的新手。我开始使用Angular7。我正在尝试下载angular中的excel文件。这是我的服务代码。
event.service.ts
getReport(reporturl: string) {
return this.http.get(reporturl, { responseType: 'arraybuffer' })
.pipe(
// tap(data => console.log('getEvent: ' + JSON.stringify(data))),
catchError(this.handleError)
);
}
在我的组件文件中,
event.ts
handleExcelDownload(data) {
this.eventService.getReport(`${data}/true`)
.subscribe(
(response: any) => {
console.log(response);
this.showFile(response, "Grid.xlsx");
// let mediaType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
// let blob = new Blob([response], { type: mediaType });
// let filename = 'Grid.xlsx';
// saveAs(blob, filename);
},
(error: any) => this.errorMessage = <any>error
);
}
private showFile(blob: any, filename: string) {
// It is necessary to create a new blob object with mime-type
// explicitly set otherwise only Chrome works like it should
let newBlob = new Blob([blob], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
let data = window.URL.createObjectURL(newBlob);
let link = document.createElement('a');
link.href = data;
link.download = filename;
link.click();
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
下载的excel总是损坏。但是在我的控制台日志中,我正在获取数组缓冲区。当我在服务器中测试时,Excel下载工作正常。请协助我解决问题。
**请求**
请求成功200次,当我预览请求时,它具有数组缓冲区。
响应预览。
但是,如果我此时手动打开此服务器URL,则文件将被下载,并且不会损坏。请协助我出问题了吗?我在互联网上尝试了许多文章,但似乎没有用。