Reading XLSX from FileReader.readAsArrayBuffer() - soares-marcio/js-xlsx GitHub Wiki

If you try to read a file using FileReader.readAsArrayBuffer() (https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer) and pass it to XLSX.read with option type:"buffer", then you'll receive a JavaScript error: Unsupported file undefined (from readSync).

If you pass it to XLSX.read with option type:"binary", then you'll receive another JavaScript error: TypeError: f.charCodeAt is not a function from firstbyte().

The typical code to read a file would be:

document.getElementById('file-object').addEventListener("change", function(e) {
  var files = e.target.files,file;
  if (!files || files.length == 0) return;
  file = files[0];
  var fileReader = new FileReader();
  fileReader.onload = function (e) {
    var filename = file.name;
    // call 'xlsx' to read the file
    var oFile = XLSX.read(e.target.result, {type: 'binary', cellDates:true, cellStyles:true});
  };
  fileReader.readAsArrayBuffer(file);
});

Example of the problem: http://codepen.io/Aymkdn/pen/YZqdqE

To fix this issue you can use the method explained at http://stackoverflow.com/questions/18582643/alternative-to-readasbinarystring-for-ie10 — so you have to pre-process the file before sending it to XLSX.read:

document.getElementById('file-object').addEventListener("change", function(e) {
  var files = e.target.files,file;
  if (!files || files.length == 0) return;
  file = files[0];
  var fileReader = new FileReader();
  fileReader.onload = function (e) {
    var filename = file.name;
    // pre-process data
    var binary = "";
    var bytes = new Uint8Array(e.target.result);
    var length = bytes.byteLength;
    for (var i = 0; i < length; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    // call 'xlsx' to read the file
    var oFile = XLSX.read(binary, {type: 'binary', cellDates:true, cellStyles:true});
  };
  fileReader.readAsArrayBuffer(file);
});

Codepen of the fix: http://codepen.io/Aymkdn/pen/aJNPMV