Reading An Excel File Using HTML 5 And jQuery

In this article, we will learn how to read an Excel file from the client side and display its contents in an HTML table by making use of the FileReader() API in HTML5 & jQuery.

The two important jQuery plugins we used here are "xlsx.core.min.js" and "xls.core.min.js" which are used to convert the data from Excel to a JSON array.

First, we will create a File Upload button, then an HTML table which is hidden first, and lastly ab Input button which upon clicking, calls the function to export Excel data to the HTML table.
  1. <input type="file" id="excelfile" />  
  2.    <input type="button" id="viewfile" value="Export To Table" onclick="ExportToTable()" />  
  3.       <br />  
  4.       <br />  
  5.    <table id="exceltable">  
  6. </table> 
Running the page will look like below.


Now, we reference the jQuery plugin files "xlsx.core.min.js" and "xls.core.min.js" in the head section.
  1. <script src="jquery-1.10.2.min.js" type="text/javascript"></script>  
  2. <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js"></script>  
  3. <script src="https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.core.min.js"></script>  
The JavaScript function ExportToTable() is given below.
  1. function ExportToTable() {  
  2.      var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;  
  3.      /*Checks whether the file is a valid excel file*/  
  4.      if (regex.test($("#excelfile").val().toLowerCase())) {  
  5.          var xlsxflag = false/*Flag for checking whether excel is .xls format or .xlsx format*/  
  6.          if ($("#excelfile").val().toLowerCase().indexOf(".xlsx") > 0) {  
  7.              xlsxflag = true;  
  8.          }  
  9.          /*Checks whether the browser supports HTML5*/  
  10.          if (typeof (FileReader) != "undefined") {  
  11.              var reader = new FileReader();  
  12.              reader.onload = function (e) {  
  13.                  var data = e.target.result;  
  14.                  /*Converts the excel data in to object*/  
  15.                  if (xlsxflag) {  
  16.                      var workbook = XLSX.read(data, { type: 'binary' });  
  17.                  }  
  18.                  else {  
  19.                      var workbook = XLS.read(data, { type: 'binary' });  
  20.                  }  
  21.                  /*Gets all the sheetnames of excel in to a variable*/  
  22.                  var sheet_name_list = workbook.SheetNames;  
  23.   
  24.                  var cnt = 0; /*This is used for restricting the script to consider only first sheet of excel*/  
  25.                  sheet_name_list.forEach(function (y) { /*Iterate through all sheets*/  
  26.                      /*Convert the cell value to Json*/  
  27.                      if (xlsxflag) {  
  28.                          var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);  
  29.                      }  
  30.                      else {  
  31.                          var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);  
  32.                      }  
  33.                      if (exceljson.length > 0 && cnt == 0) {  
  34.                          BindTable(exceljson, '#exceltable');  
  35.                          cnt++;  
  36.                      }  
  37.                  });  
  38.                  $('#exceltable').show();  
  39.              }  
  40.              if (xlsxflag) {/*If excel file is .xlsx extension than creates a Array Buffer from excel*/  
  41.                  reader.readAsArrayBuffer($("#excelfile")[0].files[0]);  
  42.              }  
  43.              else {  
  44.                  reader.readAsBinaryString($("#excelfile")[0].files[0]);  
  45.              }  
  46.          }  
  47.          else {  
  48.              alert("Sorry! Your browser does not support HTML5!");  
  49.          }  
  50.      }  
  51.      else {  
  52.          alert("Please upload a valid Excel file!");  
  53.      }  
  54.  }  
Other two functions which are called in the above function are BindTable() and BindTableHeader().
  1. function BindTable(jsondata, tableid) {/*Function used to convert the JSON array to Html Table*/  
  2.      var columns = BindTableHeader(jsondata, tableid); /*Gets all the column headings of Excel*/  
  3.      for (var i = 0; i < jsondata.length; i++) {  
  4.          var row$ = $('<tr/>');  
  5.          for (var colIndex = 0; colIndex < columns.length; colIndex++) {  
  6.              var cellValue = jsondata[i][columns[colIndex]];  
  7.              if (cellValue == null)  
  8.                  cellValue = "";  
  9.              row$.append($('<td/>').html(cellValue));  
  10.          }  
  11.          $(tableid).append(row$);  
  12.      }  
  13.  }  
  14.  function BindTableHeader(jsondata, tableid) {/*Function used to get all column names from JSON and bind the html table header*/  
  15.      var columnSet = [];  
  16.      var headerTr$ = $('<tr/>');  
  17.      for (var i = 0; i < jsondata.length; i++) {  
  18.          var rowHash = jsondata[i];  
  19.          for (var key in rowHash) {  
  20.              if (rowHash.hasOwnProperty(key)) {  
  21.                  if ($.inArray(key, columnSet) == -1) {/*Adding each unique column names to a variable array*/  
  22.                      columnSet.push(key);  
  23.                      headerTr$.append($('<th/>').html(key));  
  24.                  }  
  25.              }  
  26.          }  
  27.      }  
  28.      $(tableid).append(headerTr$);  
  29.      return columnSet;  
  30.  }  
The basic idea of the above scripts is that first we read the data from Excel file as an ArrayBuffer or raw binary data depending on the extension of the Excel file, using the FileReader() API of HTML5.
 
Then, we use jQuery plugins to convert that data into a JSON object. Next, we iterate through the JSON object and bind it to an HTML table. Our sample Excel file contains the data of certain employees, as given below.


Now, on selecting this Excel file and clicking on the "Export To Table" button, we will export the excel data to the table, as shown below.
 
That's it. Our Excel to the table is ready!

This is just a simple example of reading an Excel sheet and displaying the data from the first sheet into a table. You can always explore the script and change it to read multiple sheets and so on.

Please note that this method will be supported only on browsers which support HTML5. You can check the browsers which support HTML5 here.

Also, the above script is tested with Excel file having a maximum of 15 columns and 10,000 rows. Since this script uses iteration for binding, there may be performance issues while using huge Excel files.

Reference

https://github.com/SheetJS/js-xlsx
https://github.com/SheetJS/js-xls
 
Summary

In this article, we have learned how to make use of FileReader() API of HTML5 and jQuery to export data from an Excel file to an HTML table.
 
Hope this will be helpful!

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now