Home > Back-end >  Angular 9 - how to download and open an Excel file?
Angular 9 - how to download and open an Excel file?

Time:12-11

I have an application that downloads an Excel file. The client has requested that the file be automatically opened after download. I am hoping someone can show me what I'm doing wrong.

The URL.createObjectURL function creates a file in the downloads folder with no extension. If I add the .xlsx extension, I see that it is the correct Excel file. But if I try and open the URL generated, I get a route error:

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

The following snippet shows the existing code - which does work - and below that my unsuccessful attempt at automatically opening the document.

Any help greatly appreciated - thanks - Jon.

 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) );  
  }

CodePudding user response:

Try this below code.

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

CodePudding user response:

This wasn't exactly what I was looking for but this works and the client is happy with the solution. Instead of trying to open the file with code, I am just downloading it and telling chrome to automatically open files of that type:

Save the download:

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

Then have chrome auto open it as described in this post:

How to force open links in Chrome not download them?

  • Related