Home > Back-end >  A GET API (google sheets API) returns an excel sheet in windows 1252 encoding format. How can I down
A GET API (google sheets API) returns an excel sheet in windows 1252 encoding format. How can I down

Time:06-03

This is the response API gives

This is the code snippet.

axios.get(api , { headers: {"Authorization" : `Bearer ${token}` , "Content-Type":"application/json" , "Accept" : "*/*", "Accept-Encoding" : "gzip, deflate, br"} })
  .then(res => {
  try {     
  let fileString = iconv.decode(res.data, 'win1252');
  fs.writeFile('NodeReport.xlsx' , fileString , (error) => {
    console.log(error);
  });

  }
  catch (err){
    console.log(err);
  }
  }

);

So if I hit the API in browser it downloads the excel file , and If I save response from Postman as file it also downloads excel file . But I want to hit the API from my nodeJS code and then save the file as Excel file . I have tried to use fs.writeFile but it doesn't open the saved file , it says the format is wrong or content is corrupted. Can anyone tell how can I save this file from API response ?

CodePudding user response:

In your script, as a modification, how about the following modification?

Modified script:

axios
  .get(api, {
    headers: { Authorization: `Bearer ${token}` },
    responseType: "arraybuffer",
  })
  .then((res) => {
    try {
      fs.writeFile("NodeReport.xlsx", res.data, (error) => {
        console.log(error);
      });
    } catch (err) {
      console.log(err);
    }
  });
  • In this modification, the data is retrieved as the array buffer and saved the data as an XLSX file.

  • If the exported file is broken, please modify fs.writeFile("NodeReport.xlsx", res.data, (error) => { to fs.writeFile("NodeReport.xlsx", new Buffer.from(res.data), (error) => { and test it again.

Reference:

CodePudding user response:

const axios = require("axios").default;
const fs = require("fs");

axios
 .get(api, {
  headers: { Authorization: `Bearer ${token}` },
  responseType: "arraybuffer",
})
.then((res) => {
try {
  fs.writeFile("NodeReport.xlsx", res.data, (error) => {
    console.log(error);
  });
} catch (err) {
  console.log(err);
}
});

This script worked . Thanks for help @Tanaike

  • Related