1

below is C# WEB API Code to generate Excel :

public class FileExportController : ApiController
{

    [HttpGet]
    public HttpResponseMessage Get()
    {
        var callerContext = CallerContext.DefaultCallerContext;
        ReportingInput userInput = new ReportingInput();
        userInput.ClientOneCode = "AVON";
        string handle = Guid.NewGuid().ToString();
        var @event = new GetJobReprotDataBlEvent(callerContext, userInput);
        WebApiApplication.ApplicationInitializerObj.EventBus.Publish(@event);
        XLWorkbook wb = new FileExportEngine().ExportExcel(@event.ReportData); //this is returning XLWorkbook
        string fileName = "JobReport_" + DateTime.Now.ToString("yyyy -MM-dd HH':'mm':'ss") + ".xlsx";
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(memoryStream.ToArray())
            };
            result.Content.Headers.ContentDisposition =
                new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");

            return result;
        }

    }

When I call this API from browser, I am able to generate excel file. http://localhost/ETLScheduler/api/FileExport -- this is working when hit direct in browser

Now I want to use consume this API in angular 5 application.I have a button.On click button I call the component method downloadFile() to download the file. Below is the code :

downloadReport() {     
    this._service.downloadJobReport('AVON');
}

where downloadJobReport() is in my service file as below :

downloadJobReport(clientCode: string) {
    return this._http.get(APIs.downloadJobReport);
}

When I am running the application and click on Download button, I am getting nothing, I mean file is not downloading. Can anyone have idea,how should I update my angular code to consume the API.

Thanks in advance.

Eduard Keilholz
  • 820
  • 8
  • 27
suresh
  • 33
  • 1
  • 2
  • 10
  • Have you checked to ensure that the downloadJobReport method is executing, and also have you checked to see if the API method is being called? – Phil Jan 25 '19 at 13:23

2 Answers2

1

Problem is, that Angular expects JSON as a result. You need to configure your GET request so, that it expects something different.

public downloadJobReport(clientCode: string)): Observable<Blob> {   
    return this._http.get(APIs.downloadJobReport, { responseType: 'blob' });
}

Just a tiny question, you pass an argument clientCode to the downloadJobReport, but never use it. Maybe wise to leave that out?

Eduard Keilholz
  • 820
  • 8
  • 27
  • Thanks @nikneem I am able to download the file now,I have updated the service code as you mentioned above. I have also updated the controller code as: this._service.downloadJobReport('AVON').subscribe(data => this.downloadFile(data) ); – suresh Jan 25 '19 at 14:06
  • Where downloadFile() is as : downloadFile(data: Blob) { const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; const blob = new Blob([data], { type: contentType }); const url = window.URL.createObjectURL(blob); window.open(url); } – suresh Jan 25 '19 at 14:06
  • Thanks for your response, can you 'accept' the answer so people know the answer worked for you? You can do so by clicking the checkmark next to my answer. – Eduard Keilholz Jan 25 '19 at 14:08
  • I am passing an argument clientCode to the downloadJobReport, I will pass that in my API(I will update API code) – suresh Jan 25 '19 at 14:09
  • do you know any other way to download excel using angular(consuming ASP.Net WEB API), It will be helpful to me if you can share some link/resources which are working – suresh Jan 25 '19 at 14:12
1

As you mentioned above in comments you are using below angular code to download file:

 downloadFile(data: Blob) { 
    const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; 
    const blob = new Blob([data], { type: contentType });
    const url = window.URL.createObjectURL(blob);
    window.open(url);
}

As I also have tried this code, it is working in chrome browser but not working in IE and edge.

You may update your method somthing like below:

var downloadFile=function (file_name, content) {
var csvData = new Blob([content], { type: 'text/csv' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
    window.navigator.msSaveOrOpenBlob(csvData, file_name);
} else { // for Non-IE (chrome, firefox etc.)
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    var csvUrl = URL.createObjectURL(csvData);
    a.href =  csvUrl;
    a.download = file_name;
    a.click();
    URL.revokeObjectURL(a.href)
    a.remove();
}

};

you can refer below link for more information:

Open links made by createObjectURL in IE11

Suresh Negi
  • 372
  • 2
  • 6
  • 19