Thursday, March 15, 2018

How to Open Excel ( *.xls or *.xlsx) in Angular 4?

Problem

Angular is a platform to build SPA applications with web. If you want Angular application to access any files (like *.xls or *.xlsx) in a network share directly, the access will be blocked for security reasons. 

Solution 

Create A Web API Controller to return the file as StreamContent; Get the Blob using Angular http reponse.blob(); Create an object URL using createObjectURL(blob); Save the blob object to a file.


Details

1. Server - Controller Return Blob

var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");

Here are more details: 

2. Angular Http - Get Blob

Include the RequestOptionsArgs when you send request.



Specify the field responseType : ResponseContentType inside RequestOptionsArgs to  ResponseContentType.Blob.

Here are more details: 

3  HTML - Save Blob to File


const a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.click();
window.URL.revokeObjectURL(a.href);

Here are more details: 

No comments:

Thumbs Up to GitHub Copilot and JetBrains Resharper

Having used AI tool GitHub Copilot since 08/16/2023, I’ve realized that learning GitHub Copilot is like learning a new framework or library ...