Javascript – Converting excel file to json in nodejs

exceljavascriptjsonnode.js

I am trying to convert an excel file to json by using this api:
convert-json node api.

I am able to do it on my local machine but not on my server. Only the csv-to-json works locally and on the server. Here is my code:
https://gist.github.com/debasreedash/33efd4473ba8b344a5ac

The server crashes while trying to parse the excel file right after the first console.log. Here is what it looks like:
http://imgur.com/lzUy8sc

I thought that it was a problem with not having excel drivers on the server but after downloading and installing it did not work either. Has anyone come across this issue? If you need anymore information then let me know.

Best Answer

Use this method for easy undertsanding and parsing :

npm install --save excel'



var xls = require('excel');

xls('Sheet.xlsx', function(err, data) {
  if(err) throw err;
    // data is an array of arrays
});

As it says, the data it returns is an array of arrays. We want it to be JSON, so that we can do whatever we want with it.

This is a function that converts an array of arrays to JSON:

function convertToJSON(array) {
  var first = array[0].join()
  var headers = first.split(',');

  var jsonData = [];
  for ( var i = 1, length = array.length; i < length; i++ )
  {

    var myRow = array[i].join();
    var row = myRow.split(',');

    var data = {};
    for ( var x = 0; x < row.length; x++ )
    {
      data[headers[x]] = row[x];
    }
    jsonData.push(data);

  }
  return jsonData;
};

Then:

xlsx('tasks.xlsx', function(err,data) {
    if(err) throw err;
    //console.log(jsonDataArray(data));
    console.log(JSON.stringify(convertToJSON(data)));
    //console.log(data);
});