AAA
AAA

Reputation: 1977

NodeJs send excel file in the response with excelbuilder

After personalizing the content, I am creating an excel sheet with the following code in NodeJs

workbook.save(function (ok) {
   if (!ok)
       workbook.cancel();
   else
       console.log('Workbook saved successfully');

This saves the workbook on my server side successfully. Now I want to send this to the Angular client side. I try to send it with the following code:

__parentDir = path.dirname(process.mainModule.filename);
res.sendFile(__parentDir + '/timesheet.xlsx');

When I run it in the browser, the file is downloading successfully. But when I run it in Postman, I get the response like :

�~nL_rels/PK�~nL    docProps/PK �~nLxl/PK �~nL  xl/_rels/PK �~nL xl/theme/PK �~nLxl/worksheets/PK

Does this means the file is corrupted? If so how it is downloading properly in the browser? If it is not corrupted, then why it is not downloading in the angular code? I am trying to download it through the following code in Angular:

downloadType1(record) {
console.log(record._id);
const _this = this;
_this.appService
  .downloadTimeSheet(record._id)
  .subscribe(data => {
    console.log(data['data']);
    var urlCreator = window.URL;
    if (urlCreator) {
      var blob = new Blob([data], { type: 'application/octet-stream' });
      var url = urlCreator.createObjectURL(blob);
      var a = document.createElement("a");
      document.body.appendChild(a);
      a.href = url;
      a.download = "download.xlsx"; 
      a.click();
      window.URL.revokeObjectURL(url);
    }
  }),
  error => console.log("Error downloading the file."),
  () => console.info("OK");
}

I don't know what I am doing wrong. I have to change the code on my server side (Node) or client side(Angular)?

Upvotes: 0

Views: 2478

Answers (1)

Rakeshk Khanapure
Rakeshk Khanapure

Reputation: 420

You need to set a responseType and http header before making a get call as follows :

------------------------- ### -----------------
let getfileheaders = new HttpHeaders().set('Accept', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

return this.http.get(this.getappsecdesignfileurl, {responseType: 'blob', headers: getfileheaders});

This is important part : {responseType: 'blob', headers: getfileheaders}

Reference this link : How to download an excel (xlsx) file using Angular 5 HttpClient get method with Node/Express backend?

Upvotes: 1

Related Questions