How to parse pre-selected excel file into javascript object?

Viewed 26

i know there are tonnes of solutions regarding this but no answers for pre-selected excel file.

var ExcelToJSON = function() {

this.parseExcel = function( file ) {
  var reader = new FileReader();

  reader.onload = function(e) {
    var data = e.target.result;

    var workbook = XLSX.read(data, {
      type: 'binary'
    });
    workbook.SheetNames.forEach(function(sheetName) {
      
      var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
      var json_object = JSON.stringify(XL_row_object);
      console.log(JSON.parse(json_object));
      jQuery('#xlx_json').val(json_object);
    })
  };

  reader.readAsBinaryString(file);
 };
};

function handleFileSelect(evt) {
 var files = evt.target.files; // FileList object
 var xl2json = new ExcelToJSON();
 xl2json.parseExcel(files[0]);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);

Here instead of browsing a file, i want to open the file '../img/file.xlsx' and convert it into an object. What is the best way to do it?

1 Answers

Did you try using xlsx?

install using

npm install xlsx

to read file,

    const reader = require('xlsx')
    const file = reader.readFile('../img/file.xlsx')
Related