Angular 9-如何下载和打开Excel文件



我有一个下载Excel文件的应用程序。客户端已请求在下载后自动打开该文件。我希望有人能告诉我我做错了什么。

URL.createObjectURL函数在下载文件夹中创建一个没有扩展名的文件。如果我添加.xlsx扩展名,我会发现它是正确的Excel文件。但如果我尝试打开生成的URL,我会得到一个路由错误:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'ac88e37b-88a0-4a77-ac76-ecaddca74e39

下面的代码片段显示了现有的代码,它确实有效,下面是我尝试自动打开文档时失败的代码。

非常感谢您的帮助。

downloadExcel() {
this.dataRepositoryService.downloadExcel() 
.then( (response) => {
// This is the existing code, 
// which works and downloads the file to the downloads folder
let documentName:string = 'download-test.xlsx'; 
saveAs(response, documentName);
// I wish to replace the above 
// with code that will automatically open the downloaded file
var url = URL.createObjectURL(response); 
console.log("url: ", url); 
window.open(url);
} ) 
.catch( (error:any) => console.error(error) );  
}

试试下面的代码。

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

这不是我想要的,但这很有效,客户对解决方案很满意。我没有试图用代码打开文件,而是下载它,并告诉chrome自动打开这种类型的文件:

保存下载:

downloadExcel() {
this.dataRepositoryService.downloadExcel() 
.then( (response) => {
let documentName:string = 'download-test.xlsx'; 
saveAs(response, documentName);
} ) 
.catch( (error:any) => console.error(error) );  
}

然后让chrome自动打开它,如本文所述:

如何在Chrome中强制打开链接而不下载?

最新更新