kashan ilyas
kashan ilyas

Reputation: 352

How to download excel in response from api react.js

My api is responding like this demo [URL][https://mytutari.com/webservices/contract/exportcallnote/10377431] If i click on url it get downloaded automatically. But when I try to post some data using POST request in axios response I am getting this how to handle. API response

> PKk)S docProps/PKk)SéÙ£docProps/app.xmlÏ1ƒ0ཿB²kl‡R$êR:w°ÝCrjÀÜIrý÷M)Ô½ããÁÇ{ª]ý”-¢#¬Å±(EhÈ:jñènùEd‘5Z=B-6ˆ¢mêh†Àb–Œµ™çJÊhFð:©ÆÔô¼æÃ
> ©ï+™—dy*˳„•-Ø|þâ+Vÿ‹Z2Ÿ}ñÙmsòÕë©sšRÉ=(¹ßhÞPKk)S…]ØÓ
> docProps/core.xmlm‘ËNÃ0E÷|Eä}b;¨²’t*Ø ÎZÄÙ¦iùz’´
> uçñ=>šñ‹­n“ ú ¬)  ÏIÐH[+Ó”äyµLç$  L
> ­5X’²¨.PKk)S  docProps/PKk)SéÙ£docProps/app.xmlÏ1ƒ0ཿB²kl‡R$êR:w°ÝCrjÀÜIrý÷M)Ô½ããÁÇ{ª]ý”-¢#¬Å±(EhÈ:jñènùEd‘5Z=B-6ˆ¢mêh†Àb–Œµ™çJÊhFð:©ÆÔô¼æÃ
> ©ï+™—dy*˳„•-Ø|þâ+Vÿ‹Z2Ÿ}ñÙmsòÕë©sšRÉ=(¹ßhÞPKk)S…]ØÓ
> docProps/core.xmlm‘ËNÃ0E÷|Eä}b;¨²’t*Ø ÎZÄÙ¦iùz’´
> uçñ=>šñ‹­n“ ú ¬)  ÏIÐH[+Ó”äyµLç$  L ­5X’²¨.

API call

 ```const formData = new FormData();
formData.append("DealerID", DealerID);
formData.append("FomDate", fromdate);
formData.append("ToDate", toDate);
formData.append("FixedDateParameter", FixedDateParameter);
formData.append("export_type", export_type);
//api
const dashboardexport_response = await dashboardexport({ formData });```

dashboardexport

  let url = API + "/dashboard/dashboardexport";

  formData.append("pcp_user_id", pcp_user_id);
  formData.append("role_id", role_id);
  formData.append("user_id", user_id);
  try {
    const response = await axios.post(url, formData, { header });
    return response.data;
  } catch (error) {
    throw Error(error);
  }
};```
 

Upvotes: 17

Views: 67049

Answers (4)

Kodali444
Kodali444

Reputation: 1443

It works fine for me. Please install following modules.

//npm i file-saver
//npm i xlsx

import React from 'react'
import Button from 'react-bootstrap/Button';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

export const ExportCSV = () => {
    const[csvData,setCsvData]=React.useState([{"Name":"Gowri"}, 
    {"Name":"Siva"},{"Name":"Teja"},{"Name":"USA"}])
    const[fileName,setFileName]=React.useState("Reports");
    const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
     const fileExtension = '.xlsx';

    const exportToCSV = (csvData, fileName) => {
    const ws = XLSX.utils.json_to_sheet(csvData);
    const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' 
});
    const data = new Blob([excelBuffer], {type: fileType});
    FileSaver.saveAs(data, fileName + fileExtension);
}

return (
    <Button variant="warning" onClick={(e) => exportToCSV()}>Export</Button>
)
}

Upvotes: 4

Sam Harvey
Sam Harvey

Reputation: 101

Worth noting that the other answers forget to remove the link element from the page following download.

const url = window.URL.createObjectURL(new Blob([data.data]));
const link = document.createElement('a');

link.href = url;
link.setAttribute(
    'download',
    `${Date.now()}.xlsx`,
);

document.body.appendChild(link);
link.click();

link.remove();

Upvotes: 10

Algotechnex
Algotechnex

Reputation: 206

import axios, { AxiosRequestConfig } from 'axios';
import fs from 'fs';

export const downloadXLSFile = async () => {
    
    // Its important to set the 'Content-Type': 'blob' and responseType:'arraybuffer'.
    const headers = {'Content-Type': 'blob'};
    const config: AxiosRequestConfig = {method: 'GET', url: URL, responseType: 'arraybuffer', headers};
    
    try {
        const response = await axios(config);
        
        const outputFilename = `${Date.now()}.xls`;

        // If you want to download file automatically using link attribute.
        const url = URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', outputFilename);
        document.body.appendChild(link);
        link.click();

        // OR you can save/write file locally.
        fs.writeFileSync(outputFilename, response.data);
    } catch (error) {
        throw Error(error);
    }
}

Upvotes: 19

Lakshaya U.
Lakshaya U.

Reputation: 1181

You can do something like this:

axios.post(url, {
    method: 'GET',
    responseType: 'blob', // important
}).then((response) => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${Date.now()}.xlsx`);
    document.body.appendChild(link);
    link.click();
});

source

Upvotes: 31

Related Questions