How to Convert Excel File into JSON in Javascript

Websolutionstuff | Jul-07-2021 | Categories : jQuery

Today in this small post i will show you how to convert excel file into json in javascript. Many time we have requirment to convert excel data into json and need to import into database so here, we will convert excel file into json object using javascript.

Here, we are creating html file to export excel to json data example.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>How to Convert Excel File into JSON in Javascript</title>
    <script
      type="text/javascript"
      src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.3/xlsx.full.min.js"
    ></script>
  </head>

  <body>
    <input type="file" id="fileUpload" accept=".xls,.xlsx" /><br />
    <button type="button" id="uploadExcel">Convert</button>
    <pre id="jsonData"></pre>
  </body>
  <script>
    var selectedFile;
    document
      .getElementById("fileUpload")
      .addEventListener("change", function(event) {
        selectedFile = event.target.files[0];
      });
    document
      .getElementById("uploadExcel")
      .addEventListener("click", function() {
        if (selectedFile) {
          var fileReader = new FileReader();
          fileReader.onload = function(event) {
            var data = event.target.result;

            var workbook = XLSX.read(data, {
              type: "binary"
            });
            workbook.SheetNames.forEach(sheet => {
              let rowObject = XLSX.utils.sheet_to_row_object_array(
                workbook.Sheets[sheet]
              );
              let jsonObject = JSON.stringify(rowObject);
              document.getElementById("jsonData").innerHTML = jsonObject;
              console.log(jsonObject);
            });
          };
          fileReader.readAsBinaryString(selectedFile);
        }
      });
  </script>
</html>

 

Recommended Post
Featured Post
How To Get Current Date And Time In Vue Js
How To Get Current Date And Ti...

In this article, we will see how to get the current date and time in vue js. In vue js very simple to get the current da...

Read More

Jan-14-2022

Laravel 8 Eloquent orWhereHas Condition
Laravel 8 Eloquent orWhereHas...

In this example we will see laravel 8 eloquent orWhereHas() condition. In previous example we will learn about ...

Read More

Oct-15-2021

How To Disable Future Date In jQuery Datepicker
How To Disable Future Date In...

In this tutorial, we will see how to disable future dates in jquery datepicker. In the date picker, today's dat...

Read More

Jun-17-2022

Laravel 9 whereColumn Query Example
Laravel 9 whereColumn Query Ex...

In this article, we will see laravel 9 whereColumn() query example. The whereCoulmn method is used to verify whethe...

Read More

Oct-21-2022