The weird characters you got from reading the Excel file from the FileReader
API comes from the structure of the file that differs a lot from a text file.
So reading it as text
with the FileReader
API will give those weirds character as a result.
What you can do is to use the FileReader
API to read it as a binary string
.
At this point if you try to log that binary string
you will also get weirds characters.
In order to get your file content you need to parse that binary string
to extract the data it contains. This can be done quite easily using SheetJS.
import { read, writeFileXLSX, utils } from "https://cdn.sheetjs.com/xlsx-0.18.7/package/xlsx.mjs";
const workbook = read(data, {
type:'binary',
});
data
is the binary string
resulting from reading an Excel file as a binary string
with the FileReader
API.
workbook
is an object that contains all the data of your file.
The workbook.Sheets
instruction will give you access to all the sheets
that are in the file.
workbook.Sheets.sheet1
will give you access to the content of the first sheet
of the file.
All the related arrays are from the {key:value}
type.
The content of a sheet
accessed this way is a single dimension object
array
wich contains all the cells of the sheet
starting from the first cell of the header to the last cell wich contains data.
Each of those cells has a key like this 'A1'
, 'B250'
, 'J3'
This array also have two more entries with those keys '!margin'
and '!ref'
:
'!margin'
refers to cells margins so it may not represent any interest.
'!ref'
is more interesting as it contains the plage of cells containing data wich is a string
like this 'A1:J215'
from it you could get the amount of lines or the char of the last column.
If you want more informations you could check the SheetJS documentation and there is a more detailed example here : How to read an excel file contents on client side?
Note :
If you want to use this import statement in an html
page you’ll need to do it inside those scripts tags
: <script type="module" defer> ... </script>
Here is a codepen where you can test this method. There’s only the most basic method. There are some shorter ways to do the same by using the SheetJS utils
functions to convert directly the sheet
content to another format.
In this tutorial you can find how to read excel file using JavaScript and display excel sheet data on web page in HTML table format using JavaScript. In previous, one of our tutorial, in which we have already seen how to convert HTML table data into Excel file by using SheetJS library. Now in this tutorial also we will use SheetJS JavaScript library and by using JavaScript library, we will convert Excel file data to HTML table and display on web page. Here under this tutorial, we will not use jQuery and Ajax server side script for fetch data from excel and display on web page. Now lets start seeing it!
First we have to include Bootstrap Stylesheet and SheetJS library link at header of our HTML page.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
After this under this HTML page, we have to create one file tag for select file excel from local computer.
<input type="file" id="excel_file" />
And below this file, we have to create one division tag for display excel sheet data on web page in HTML table format.
<div id="excel_data" class="mt-5"></div>
Next we have to move on write JavaScript code, so first store file tag property under one variable.
const excel_file = document.getElementById('excel_file');
Next we have to write javascript code on change event, so when user have select file from local computer using file tag, then javascript code must be execute.
excel_file.addEventListener('change', (event) => {
});
Under this change event code first we want to check selected file format is .xls or .xlsx. If selected file is not excel file then it will display error on web page, and if select file is excel then it will proceed for display excel file data on web page.
if(!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type))
{
document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';
excel_file.value = '';
return false;
}
After check validation error, now read the file using FileReader object. Here file must be read ads ArrayBuffer by pass the file object using event.target.files[0].
var reader = new FileReader();
reader.readAsArrayBuffer(event.target.files[0]);
IF the selected file is proper excel file then we need to convert what we have got from FileReader object to Unit8Array object by passing Filereader result into Unit8Array constructor.
var data = new Uint8Array(reader.result);
Next we have pass this Unit8Array data in SheetJS read() function, and it will return selected excel workbook object.
var work_book = XLSX.read(data, {type:'array'});
After getting workbook object, next we have to get sheet name of selected excel file. So here SheetNames variable will return sheet name in array format.
var sheet_name = work_book.SheetNames;
Once we have get sheet name, now we want to get first sheet data in JSON format, so this we can get by SheetJS sheet_to_json() function by passing workbook first sheet name.
var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {header:1});
Once we have get first sheet data in JSON format, next we have to simply write JavaScript code and convert that JSON data into HTML format and display under division tag wih id excel_data. So it will display excel file data on web page in HTML table format.
if(sheet_data.length > 0)
{
var table_output = '<table class="table table-striped table-bordered">';
for(var row = 0; row < sheet_data.length; row++)
{
table_output += '<tr>';
for(var cell = 0; cell < sheet_data[row].length; cell++)
{
if(row == 0)
{
table_output += '<th>'+sheet_data[row][cell]+'</th>';
}
else
{
table_output += '<td>'+sheet_data[row][cell]+'</td>';
}
}
table_output += '</tr>';
}
table_output += '</table>';
document.getElementById('excel_data').innerHTML = table_output;
}
So once you have follow all above steps then you can check ouput in browser. So when we have select excel file then it will display excel sheet data on web page in HTML table format without refresh of web page. So in this tutorial, we have seen how to convert Excel file to HTML table at client-side by using SheetJS JavaScript library at client-side. Below you can find complete source code.
Full Source Code
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>Convert Excel to HTML Table using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
</head>
<body>
<div class="container">
<h2 class="text-center mt-4 mb-4">Convert Excel to HTML Table using JavaScript</h2>
<div class="card">
<div class="card-header"><b>Select Excel File</b></div>
<div class="card-body">
<input type="file" id="excel_file" />
</div>
</div>
<div id="excel_data" class="mt-5"></div>
</div>
</body>
</html>
<script>
const excel_file = document.getElementById('excel_file');
excel_file.addEventListener('change', (event) => {
if(!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type))
{
document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';
excel_file.value = '';
return false;
}
var reader = new FileReader();
reader.readAsArrayBuffer(event.target.files[0]);
reader.onload = function(event){
var data = new Uint8Array(reader.result);
var work_book = XLSX.read(data, {type:'array'});
var sheet_name = work_book.SheetNames;
var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {header:1});
if(sheet_data.length > 0)
{
var table_output = '<table class="table table-striped table-bordered">';
for(var row = 0; row < sheet_data.length; row++)
{
table_output += '<tr>';
for(var cell = 0; cell < sheet_data[row].length; cell++)
{
if(row == 0)
{
table_output += '<th>'+sheet_data[row][cell]+'</th>';
}
else
{
table_output += '<td>'+sheet_data[row][cell]+'</td>';
}
}
table_output += '</tr>';
}
table_output += '</table>';
document.getElementById('excel_data').innerHTML = table_output;
}
excel_file.value = '';
}
});
</script>
Introduction
In some use cases, we have a complicated Excel sheet to share on our personal website and we would like to make it interactive. Fortunately, Microsoft allows the user to do so via OneDrive and it supports both HTML iframe
and JavaScript.
In this blog post, I would like the discuss how to embed Excel sheet in HTML, the issues that I encountered, and how to fix the issues.
Embed Excel Sheet in HTML
Generate Code
Once the Excel sheet has been created or uploaded to Microsoft OneDrive, generating the Excel embed code could be as easy as clicking File → Share → Embed → Generate HTML.
Insert Code
Then we could copy the HTML iframe
code or the JavaScript code and insert it into our website.
Using the default HTML iframe
code will result in an embedded Excel sheet as follows. If you see lots of white spaces before the table, it is a bug from Microsoft and the bug will show in most of the browsers except the Brave browser.
1 |
<iframe width="402" height="346" frameborder="0" scrolling="no" src="https://onedrive.live.com/embed?resid=6C685993F809A9F8%212757&authkey=%21AABR6KgqMF_ImYs&em=2&wdAllowInteractivity=False&AllowTyping=True&wdDownloadButton=True&wdInConfigurator=True&wdInConfigurator=True&edesNext=true&ejss=false"></iframe> |
Using the default JavaScript code will result in an embedded Excel sheet as follows.
1 |
<div id="myExcelDiv" style="width: 402px; height: 346px"></div> |
Fix JavaScript Issues
The width of the embedded Excel sheet seems to be a problem, but we could modify the width values in the style. A bigger problem is, unlike the iframe
embedding, the JavaScript embedding does not allow the user to input values and one HTML can only have one Excel sheet embedded (without problems) because the div id
is a pre-defined value myExcelDiv
.
Personally, I favor the JavaScript embedding over the HTML iframe
embedding. So we would like to try solving those problems on our own.
We noticed that there is an argument wdAllowInteractivity=0
in the src
for both JavaScript and iframe
, although it does not prevent the user from typing in iframe
, changing it to 1
allows the user to type successfully.
In addition, wdDivId=%22myExcelDiv%22
is the place for specifying custom div id
for embedding Excel sheets. We could use new div id
here.
Finally, we can also make the webpage opening a little bit faster by making the loading of JavaScript async
.
Fix Preview
The fixed JavaScript code is as follows. We could see that now the embedded Excel sheet looks pretty nice.
1 |
<div id="myExcelDiv1" style="width: 100%; height: 400px"></div> |
This article shows you how you display the Excel data in an HTML table using SheetJS in Javascript. SheetJS is a javascript library used to work with various spreadsheet formats. In another article, we explained Converting Excel file data to JSON using the SheetJS library in Javascript. Today in this article, we will explain how to display Excel spreadsheet data in an HTML table using javascript.
Here first we convert the Excel data into JSON format then JSON data will be shown in HTML tabular format. Let’s see how it can be done.
SheetJS Library
SheetJS is a powerful library written in pure Javascript. It is a Parser and writer for various spreadsheet formats.
How to use SheetJS?
As it is a javascript library, we have to include it in the HTML document to use this library. There are various CDN links that can be used to include it. Let’s see one of the CDN links below:
Now let’s see the below script that we have to include in the <head> tag of the HTML document,
<script
src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.min.js"></script>
Follow the below steps to display excel data in the HTML table:
- Define HTML
- Includes the SheetJS library
- Write the Javascript logic to upload and validate the Excel file
- Read the Excel data into JSON format
- Convert JSON data to the HTML table
1. Define HTML
First, we will define the HTML to allow users to upload an Excel file and display it in tabular format. We will define an HTML <input>
tag with type=”file” to choose an Excel file. And a <button>
tag to upload the file and an HTML <table> tag to display the data.
Let’s define the below HTML code in an HTML document file:
<h1>Upload an excel file to display in HTML Table</h1> <!-- Input element to upload an excel file --> <input type="file" id="file_upload" /> <button onclick="upload()">Upload</button> <br><br> <!-- table to display the excel data --> <table id="display_excel_data"></table>
2. Includes the SheetJS library
Include the CDN link of library xlsx.min.js in the <head>
tag of an HTML file as follows:
<head> <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.min.js"></script> </head>
3. Write the Javascript logic to upload and validate the Excel file
We will define a javascript upload()
method to upload and validate the Excel file. The upload()
method will allow users to upload a valid Excel file only. Let’s see the below logic that we have to write in <script>
tag:
// Method to upload a valid excel file function upload() { var files = document.getElementById('file_upload').files; if(files.length==0){ alert("Please choose any file..."); return; } var filename = files[0].name; var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase(); if (extension == '.XLS' || extension == '.XLSX') { //Here calling another method to read excel file into json excelFileToJSON(files[0]); }else{ alert("Please select a valid excel file."); } }
4. Read Excel file in Javascript and convert it into JSON format
We have defined a javascript method excelFileToJSON()
that will read the Excel file and convert the data into JSON format. Inside excelFileToJSON()
, we have read the data of the Excel file by using a file reader as a binary string using readAsBinaryString()
method. After that, we used XLSX which has a built-in facility to convert our binary string into a JSON object. And the XLSX.utils.sheet_to_json()
method is used to read sheet data in JSON.
Let’s see the code below:
//Method to read excel file and convert it into JSON function excelFileToJSON(file){ try { var reader = new FileReader(); reader.readAsBinaryString(file); reader.onload = function(e) { var data = e.target.result; var workbook = XLSX.read(data, { type : 'binary' }); var result = {}; var firstSheetName = workbook.SheetNames[0]; //reading only first sheet data var jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheetName]); alert(JSON.stringify(jsonData)); //displaying the json result into HTML table displayJsonToHtmlTable(jsonData); } }catch(e){ console.error(e); } }
5. Convert JSON data to the HTML Table using Javascript
Now we have defined a javascript method displayJsonToHtmlTable()
to display the JSON data in an HTML table.
Let’s see the code:
//Method to display the data in HTML Table function displayJsonToHtmlTable(jsonData){ var table=document.getElementById("display_excel_data"); if(jsonData.length>0){ var htmlData='<tr><th>Student Name</th><th>Address</th><th>Email ID</th><th>Age</th></tr>'; for(var i=0;i<jsonData.length;i++){ var row=jsonData[i]; htmlData+='<tr><td>'+row["Student Name"]+'</td><td>'+row["Address"] +'</td><td>'+row["Email ID"]+'</td><td>'+row["Age"]+'</td></tr>'; } table.innerHTML=htmlData; }else{ table.innerHTML='There is no data in Excel'; } }
Display Excel data in HTML Table [complete example]
This example shows you Excel to HTML table Conversion. Let’s see the complete code below (putting all the above code in a single HTML file):
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Excel to HTML Table | Javacodepoint</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.min.js"></script> </head> <body> <h1>Upload an excel file to display in HTML Table</h1> <!-- Input element to upload an excel file --> <input type="file" id="file_upload" /> <button onclick="upload()">Upload</button> <br> <br> <!-- table to display the excel data --> <table id="display_excel_data" border="1"></table> <script> // Method to upload a valid excel file function upload() { var files = document.getElementById('file_upload').files; if(files.length==0){ alert("Please choose any file..."); return; } var filename = files[0].name; var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase(); if (extension == '.XLS' || extension == '.XLSX') { //Here calling another method to read excel file into json excelFileToJSON(files[0]); }else{ alert("Please select a valid excel file."); } } //Method to read excel file and convert it into JSON function excelFileToJSON(file){ try { var reader = new FileReader(); reader.readAsBinaryString(file); reader.onload = function(e) { var data = e.target.result; var workbook = XLSX.read(data, { type : 'binary' }); var result = {}; var firstSheetName = workbook.SheetNames[0]; //reading only first sheet data var jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheetName]); //displaying the json result into HTML table displayJsonToHtmlTable(jsonData); } }catch(e){ console.error(e); } } //Method to display the data in HTML Table function displayJsonToHtmlTable(jsonData){ var table=document.getElementById("display_excel_data"); if(jsonData.length>0){ var htmlData='<tr><th>Student Name</th><th>Address</th><th>Email ID</th><th>Age</th></tr>'; for(var i=0;i<jsonData.length;i++){ var row=jsonData[i]; htmlData+='<tr><td>'+row["Student Name"]+'</td><td>'+row["Address"] +'</td><td>'+row["Email ID"]+'</td><td>'+row["Age"]+'</td></tr>'; } table.innerHTML=htmlData; }else{ table.innerHTML='There is no data in Excel'; } } </script> </body> </html>
Test and Live Demo
Let’s assume a sample Excel file(students.xlsx) that we are going to upload. As you can see in the below image this Excel file contains the student’s data(name, address, email id, and age).
Let’s see the result once we upload the above Excel file to this application.
Conclusion
In this tutorial, you have seen how you display the Excel file data in an HTML Table using Javascript. You have seen here, that can be easily done by using the SheetJS library. As you have seen this library has the capability to convert binary strings to JSON format that is used here to display in an HTML table.
Related articles:
- Convert JSON data into HTML table using jquery
- Convert Excel file data to JSON in Javascript
- How to read Excel files in Java using Apache POI?
- How to create password-protected Excel in Java?
- How to write data to an existing Excel file in Java?
You may also like:
How to create a Stopwatch in JavaScript?
File upload validations in javascript
Drag & Drop or Browse – File upload Feature in JavaScript
Preview an image before uploading using Javascript
Preview an image before uploading using jQuery
Introduction
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.
- <input type=«file» id=«excelfile» />
- <input type=«button» id=«viewfile» value=«Export To Table» onclick=«ExportToTable()» />
- <br />
- <br />
- <table id=«exceltable»>
- </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.
- <script src=«jquery-1.10.2.min.js» type=«text/javascript»></script>
- <script src=«https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js»></script>
- <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.
- function ExportToTable() {
- var regex = /^([a-zA-Z0-9s_\.-:])+(.xlsx|.xls)$/;
- if (regex.test($(«#excelfile»).val().toLowerCase())) {
- var xlsxflag = false;
- if ($(«#excelfile»).val().toLowerCase().indexOf(«.xlsx») > 0) {
- xlsxflag = true;
- }
- if (typeof (FileReader) != «undefined») {
- var reader = new FileReader();
- reader.onload = function (e) {
- var data = e.target.result;
- if (xlsxflag) {
- var workbook = XLSX.read(data, { type: ‘binary’ });
- }
- else {
- var workbook = XLS.read(data, { type: ‘binary’ });
- }
- var sheet_name_list = workbook.SheetNames;
- var cnt = 0;
- sheet_name_list.forEach(function (y) {
- if (xlsxflag) {
- var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
- }
- else {
- var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
- }
- if (exceljson.length > 0 && cnt == 0) {
- BindTable(exceljson, ‘#exceltable’);
- cnt++;
- }
- });
- $(‘#exceltable’).show();
- }
- if (xlsxflag) {
- reader.readAsArrayBuffer($(«#excelfile»)[0].files[0]);
- }
- else {
- reader.readAsBinaryString($(«#excelfile»)[0].files[0]);
- }
- }
- else {
- alert(«Sorry! Your browser does not support HTML5!»);
- }
- }
- else {
- alert(«Please upload a valid Excel file!»);
- }
- }
Other two functions which are called in the above function are BindTable() and BindTableHeader().
- function BindTable(jsondata, tableid) {
- var columns = BindTableHeader(jsondata, tableid);
- for (var i = 0; i < jsondata.length; i++) {
- var row$ = $(‘<tr/>’);
- for (var colIndex = 0; colIndex < columns.length; colIndex++) {
- var cellValue = jsondata[i][columns[colIndex]];
- if (cellValue == null)
- cellValue = «»;
- row$.append($(‘<td/>’).html(cellValue));
- }
- $(tableid).append(row$);
- }
- }
- function BindTableHeader(jsondata, tableid) {
- var columnSet = [];
- var headerTr$ = $(‘<tr/>’);
- for (var i = 0; i < jsondata.length; i++) {
- var rowHash = jsondata[i];
- for (var key in rowHash) {
- if (rowHash.hasOwnProperty(key)) {
- if ($.inArray(key, columnSet) == -1) {
- columnSet.push(key);
- headerTr$.append($(‘<th/>’).html(key));
- }
- }
- }
- }
- $(tableid).append(headerTr$);
- return columnSet;
- }
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 that support HTML5. You can check the browsers which support HTML5 here.
Also, the above script is tested with an 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!