0

I am trying to parse xlsx file and save as a table (Along the lines of Excel to JSON javascript code? which is working fine for xls files). However, I am unable to convert to json and display as a table. Please find below the code snippet. Can anyone please guide how to close on this.

function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();

// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
    var data = e.target.result;
    var cfb = XLSX.read(data, {type: 'binary'});
    var wb = XLSX.parse_xlscfb(cfb);
    wb.SheetNames.forEach(function(sheetName) {
        // Obtain The Current Row As CSV
        //var sCSV = XLSX.utils.make_csv(wb.Sheets[sheetName]); 
        var data = XLSX.utils.make_json(wb.Sheets[sheetName], {header:1}); 
        alert(data.length);
        //var columns = data[0].split(",");  
        $.each(data, function( indexR, valueR ) {
            var sRow = "<tr>";
            $.each(data[indexR], function( indexC, valueC ) {
                sRow = sRow + "<td>" + valueC + "</td>";
            });
            sRow = sRow + "</tr>";
            $("#my_file_output").append(sRow);
        });
    });
};

// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);

}

Community
  • 1
  • 1
rafavinu
  • 305
  • 4
  • 20

1 Answers1

1

use this code : note: use jszip.js and xlsx.js library

reader.onload = function(evt) {
  debugger;
  var data = evt.target.result;
  //var xlsx = XLSX.read(data, {type: 'binary'});
  var arr = String.fromCharCode.apply(null, new Uint8Array(data));
  var xlsx = XLSX.read(btoa(arr), {
    type: 'base64'
  });
  result = xlsx.Strings;
  result = {};
  xlsx.SheetNames.forEach(function(sheetName) {
    var rObjArr = XLSX.utils.sheet_to_row_object_array(xlsx.Sheets[sheetName]);
    if (rObjArr.length > 0) {
      result[sheetName] = rObjArr;
    }
  });
  return result;
 // that.b64toBlob(xlsx, "binary");
};
reader.readAsArrayBuffer(file);

use readAsArrayBuffer method which will support on all browser.

Mahendra Kulkarni
  • 1,437
  • 2
  • 26
  • 35
  • have you added "jszip.js" and "xlsx.js" library – Mahendra Kulkarni May 31 '16 at 04:30
  • Yes, have included both, tried to alert result at the point of return result. Nothing is displaying!! – rafavinu May 31 '16 at 11:07
  • I'm not sure why it needs the arr, xlsx song and dance, but it's finally working where following the usual "var xlsx = XLSX.read(data, {type: 'binary'});" throws errors. – rik Jun 28 '17 at 14:23