javascriptjsonhtmlxlsfilereader

How to parse Excel (XLS) file in Javascript/HTML5


I am able to read Excel file via FileReader but it outputs text as well as weird characters with it. I need to read xls file row-wise, read data in every column and convert it to JSON.

How to read xls file row by row?


Solution

  • Below Function converts the Excel sheet (XLSX format) data to JSON. you can add promise to the function.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
    <script>
    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) {
            // Here is your object
            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_object);
    
          })
    
        };
    
        reader.onerror = function(ex) {
          console.log(ex);
        };
    
        reader.readAsBinaryString(file);
      };
    };
    </script>
    

    Below post has the code for XLS format Excel to JSON javascript code?