Search code examples
node.jsxls

Crating XLS file from binary data in node.js


I received the binary data as response from http request.

In C# I convert the data to byteArray and writhing the byteArray into file creates a readable xls file.

C# Code:

 HttpResponseMessage httpResponseMessage = _httpClient.GetAsync(endPoint).Result;
 var httpResponseByteArray = httpResponseMessage.Content.ReadAsByteArrayAsync().Result;
 File.WriteAllBytes("plateList.xls", httpResponseByteArray);

I am looking for a way to implement the same thing in node js.

I`ve tried these methods so far but each created a non-readable file:

 const Excel = require('exceljs');

First try - node.js

 var dataBinary = response.data;
 var workbook = new Excel.Workbook(dataBinary);
 await workbook.xlsx.writeFile("Test.xls")
         .then(function (err) {
            if (err) throw err;
            console.log('\x1b[32m%s\x1b[0m', "Create excel file successfully");
          });

Secound try - node.js

 var bufferData = Buffer.from(response.data);
 var workbook = new Excel.Workbook(dataBinary);
 await workbook.xlsx.writeFile("Test.xls")
         .then(function (err) {
            if (err) throw err;
            console.log('\x1b[32m%s\x1b[0m', "Create excel file successfully");
          });

Other library:

 const fs = require('fs');

Third try - node.js

 fs.writeFileSync("Test.xls", response.data);

Fourth try - node.js

 fs.writeFileSync("Test.xls",  Buffer.from(response.data));

And more but nothing work to me


Solution

  • // response.data as a arrayBuffer
    var data = response.data;
    var arr = new Array();
    for (var i = 0; i != data.length; ++i)
        arr[i] = String.fromCharCode(data[i]);
    var bstr = arr.join("");
    
    /* Call XLSX */
    var workbook = XLSX.read(bstr, {
        type: "binary"
    });
    
    /* Create the file*/
    XLSX.writeFile(workbook, "carNumbersAllowedFromLPRCamera.xls");
    
    /* Get the work sheet name */
    var first_sheet_name = workbook.SheetNames[0];
    
    /* Get worksheet */
    var worksheet = workbook.Sheets[first_sheet_name];
    
    /* Convert it to json*/
    let xlsData = XLSX.utils.sheet_to_json(worksheet, {
        raw: true
    })