5

I have two separate projects. Client: React, Server: NodeJS

I create excel on the NodeJS side by submitting a form by React.

I want to download this excel from React side. However, I couldn't download it.

NodeJS code

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
  workbook.xlsx.write(res)
      .then(function(){
          res.end();
      });

NodeJS return network layer

enter image description here

First try React.js code

 startDownload(response,"resobyte.xlsx")

function startDownload(file, fileName) {
    const url = window.URL.createObjectURL(new Blob([file]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    link.parentNode.removeChild(link);
}

Second try React.js code

  let blob = new Blob([response], {type: 'vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
            FileSaver.saveAs(blob, 'fileName.xlsx");

The file has been downloaded.

My React Service Call

export const createExcel = async (model) => {
  let response = () => {
      return new Promise(function(resolve, reject) {
        fetch(API_URL + '/api/excel/create', {
          method: 'POST',
          responseType: 'arrayBuffer',
          headers: {
          'Content-Type': 'application/json',
          'x-access-token' : TokenService.getToken()
          },
          body: JSON.stringify(model),
        }).then(response => {
          resolve(response);
        });
      });
    };
    let responseData = await response();
    return responseData;
}

Error open excel file

enter image description here

General Grievance
  • 4,555
  • 31
  • 31
  • 45
resobyte
  • 116
  • 7

0 Answers0