Содержание
- Read Excel file using Javascript (XLSX or XLS)
- Read XLSX using Javascript
- Read XLS file using Javascript
- Convert Excel to JSON using Javascript
- Webslesson
- PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter, Laravel Tutorial
- Monday, 26 July 2021
- How to Display Excel Data in HTML Table using JavaScript
- Copy/Paste from Excel to a web page
- 9 Answers 9
- How to parse Excel (XLS) file in Javascript/HTML5
- 16 Answers 16
- Upload an excel file here and you can get the data in JSON format in console :
- Html Code
- Javascript
- How to Import/Export Data From Excel In MVC
- Download Demo Application
- Create Application
- Step 1 :
- Step 2 :
- Step 3 :
- Step 4 :
- Step 5 :
- Step 6 :
- Step 7 :
- Step 8 :
- Step 9 :
- Step 10 :
- Step 11 :
- Step 12 :
- Step 13 :
- Summary
Read Excel file using Javascript (XLSX or XLS)
In the previous post, I have explained how we can read csv file using javascript and HTML 5 filereader, now in this post, I have explained how we can use external library like xlsx to parse or read excel file using javascript and show it’s contents in HTML table. When file is uploaded using Javascript, it is read as Binary string initially, and then binary data is read using xlsx plugin.
Read XLSX using Javascript
Let’s beging by adding simple HTML file input and button to upload file
I have also included empty HTML div to create table inside it from our Excel file.
Now, we will create the function to upload the file and process the Excel file to get data from it and convert it into HTML table.
In the above Javascript code, we are first adding references of XLSX plugin files and then adding two functions
- UploadProcess: Uploads the file on button click and convert it into Binary data, it also check if Browser is IE then process accordingly to convert file into binary.
- ProcessExcel: this function takes the binary data, reads the Sheet name, create Table element and append each row in it.
I have explained lines of code using Comment.
Suppose our sample Excel file looks like this
So, if use the above code in HTML/Javascript, output will be as below
Read XLS file using Javascript
In a Similar way, we can read .xls (excel) file also and show it in HTML table, I will repeat the same code, just few lines of code is different, also we will be using different plugin in it which is for .xls
The XLS file upload code is the same as .XLSX one was, here are the changes
- We included difference JS plugin file :
- Changed a few lines of code for the function «GetTableFromExcel»
The rest of the code remains the same.
Note: You need to pass .xls file in this code to make it work.
Convert Excel to JSON using Javascript
You can also upload excel and then convert it to JSON data and proceed with it further.
Here is the fiddle: https://jsfiddle.net/aszchkr0/ using which you can test the above code, just to search excel file and once value is changed you will find JSON result in textarea.
In the above code, we are reading excel using XLSX plugin, then we loop through each sheet and get XL row object and further convert it to JSON.
Источник
Webslesson
PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter, Laravel Tutorial
Monday, 26 July 2021
How to Display Excel Data in HTML Table using JavaScript
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.
After this under this HTML page, we have to create one file tag for select file excel from local computer.
And below this file, we have to create one division tag for display excel sheet data on web page in HTML table format.
Next we have to move on write JavaScript code, so first store file tag property under one variable.
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.
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.
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].
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.
Next we have pass this Unit8Array data in SheetJS read() function, and it will return selected excel workbook object.
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.
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.
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.
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.
Источник
Copy/Paste from Excel to a web page
Is there a standard way or library to copy and paste from a spreasheet to a web form? When I select more than one cell from Excel I (obviously) lose the delimiter and all is pasted into one cell of the web form. Does it have to be done in VB? or could the processing be done once the paste action is started on the web form?
9 Answers 9
You don’t lose the delimiters, the cells are separated by tabs ( t ) and rows by newlines ( n ) which might not be visible in the form. Try it yourself: copy content from Excel to Notepad, and you’ll see your cells nicely lined up. It’s easy then to split the fields by tabs and replace them with something else, this way you can build even a table from them. Here’s a example using jQuery:
So in essence, this script creates an HTML table from pasted Excel data.
In response to the answer by Tatu I have created a quick jsFiddle for showcasing his solution:
On OSX and Windows , there are multiple types of clipboards for different types of content. When you copy content in Excel, data is stored in the plaintext and in the html clipboard.
The right way (that doesn’t get tripped up by delimiter issues) is to parse the HTML. http://jsbin.com/uwuvan/5 is a simple demo that shows how to get the HTML clipboard. The key is to bind to the onpaste event and read
For any future googlers ending up here like me, I used @tatu Ulmanen’s concept and just turned it into an array of objects. This simple function takes a string of pasted excel (or Google sheet) data (preferably from a textarea ) and turns it into an array of objects. It uses the first row for column/property names.
Hopefully it helps someone in the future.
The same idea as Tatu(thanks I’ll need it soon in our project), but with a regular expression.
Which may be quicker for large dataset.
UPDATE: This is only true if you use ONLYOFFICE instead of MS Excel.
There is actually a flaw in all answers provided here and also in the accepted one. The flaw is that whenever you have an empty cell in excel and copy that, in the clipboard you have 2 tab chars next to each other, so after splitting you get one additional item in array, which then appears as an extra cell in that row and moves all other cells by one. So to avoid that you basically need to replace all double tab (tabs next to each other only) chars in a string with one tab char and only then split it.
An updated version of @userfuser’s jsfiddle is here to fix that issue by filtering pasted data with removeExtraTabs
Источник
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?
16 Answers 16
Below Function converts the Excel sheet (XLSX format) data to JSON. you can add promise to the function.
Below post has the code for XLS format Excel to JSON javascript code?
Old question, but I should note that the general task of parsing XLS files from javascript is tedious and difficult but not impossible.
I have basic parsers implemented in pure JS:
Both pages are HTML5 File API-driven XLS/XLSX parsers (you can drag-drop your file and it will print out the data in the cells in a comma-separated list). You can also generate JSON objects (assuming the first row is a header row).
The test suite http://oss.sheetjs.com/ shows a version that uses XHR to get and parse files.
Upload an excel file here and you can get the data in JSON format in console :
This is a combination of the following Stackoverflow posts:
This code can help you
Most of the time jszip.js is not working so include xlsx.full.min.js in your js code.
Html Code
Javascript
If you want the simplest and tiniest way of reading an *.xlsx file in a browser then this library might do:
In the example above data is raw string data. It can be parsed to JSON with a strict schema by passing schema argument. See API docs for an example of that.
Thank you for the answer above, I think the scope (of answers) is completed but I would like to add a «react way» for whoever using react.
Create a file called importData.js:
Then you can use the component in the render method like:
would set the data to its own state, you can access Excel data in the «parent component» by following this:
Simplest way to do it using CDN with plain javascript
Simplest way to it using plain javascript.
If you are ever wondering how to read a file from server this code might be helpful.
- File should be in the server (Local/Remote).
- You will have to setup headers or have CORS google plugin.
include the xslx.js , xlsx.full.min.js , jszip.js
add a onchange event handler to the file input
This is for react js
Below code will work in reading XLSX file using Javascript
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.
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 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 :
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.
Источник
How to Import/Export Data From Excel In MVC
In software development, Import/Export is a technique to read and write data from files. We have multiple data file format to store our valuable data like png, jpg, xls, xlsx, pdf, txt, sql, etc, from where we need to read and write data. Every technology has its own technique to read and write data from files. Here, I am using the c# programming language to perform this task through ASP.NET MVC Web Application.
Jump to Section
Download Demo Application
Create Application
Note: I am using visual studio 2013, Follow the steps to create your application for Import and export excel file data.
Step 1 :
- Open Visual Studio.
- Create a new application click on File > New > Project > Templates > Web > ASP.NET MVC 4 Web Application.
- Enter the project name in Name text box like “Import_Export“.
- Select the location from Location drop-down where you want to save your project.
- Select “Add to solution” from Solution drop-down.
- Click Ok.
Note: If a new window is open then select Empty then Click Ok.
Now, new Empty MVC application is created successfully.
Step 2 :
- Add a Model class, Open solution explorer > Right click on Model folder > Add > Class
- Enter class name as “Employee.cs“.
- Add the following code to Employee.cs class.
Step 3 :
- Add another class, Open solution explorer > Right click on Model folder > Add > Class
- Enter class name as “ExcelData.cs“.
- Click the Add button to add it to your project.
Step 4 :
- Open your Project within the Solution Explorer
- Right-click the References folder and Choose Add Reference.
- Find and select the Excel assembly that was contained within your download.
- Click the Ok button to add it to your Project.
You can easily find and include this library via NuGet within your application as well through the following steps:
- Right-click your Project within the Solution Explorer
- Choose the “Manage NuGet Packages” option that appears
- Search for “Excel Data Reader” within the search box
- Click “Install” on the first option that appears.
Both of these approaches will add the appropriate Excel assembly references to your application. Then when you actually need to execute a query within your code, you might use something like this:
Step 5 :
Add the following code to ExcelData.cs class.
Step 6 :
- Add a controller, Open solution explorer > Right click on Controllers folder > Add > Controller..
- Enter Controller name Like “HomeController“.
- Click on Add button.
Step 7 :
Reference to access the model classes
- Add the Models references to the controller.
- And also add the following namespace for data and file communication.
- Replace the Index() ActionResult method with following code.
- Add the following ActionResult method to the HomeController for Import/Export Excel file.
Step 8 :
- Add a view, Right click on Index method > Add view > Click Add button.
- Replace the Index.cshtml content with the following content.
Step 9 :
- Create an Excel file with two column “Id” and “Expectation“.
- Add some data in excel sheet.
Id | Expectation |
1 | Acknowledge emails within 2 hours |
2 | Be prepared for Daily Stand-up at 10:15 am |
3 | Commit code updates to repository daily |
4 | Ensuring the timely delivery of work as per quality standards. |
5 | Every update to production server must be signed off by QA |
6 | Follow variable naming conventions & guidelines for the particular platform. |
7 | Have 90% understanding of the project through SRS doc before commencing work. |
8 | Maintain politeness while talking to other colleagues |
9 | No use of social media either with phone or desktop. |
10 | Provide Developer Sign Off before handing over builds to QA |
- Save excel sheet where you want to save.
Step 10 :
- Build your application.
- Run the application.
- Your Index.cshtml user interface looks like the following result.
Step 11 :
- Click “Choose file” button.
- Go to the file location where your excel file is saved.
- Select Excel file.
- Click ok.
Step 12 :
- Click Import from Excel button for import data from excel sheet and bind with HTML table.
- The following UI is shown, After clicking on Import from Excel button.
Step 13 :
- Click “Export to Excel” button for export data from HTML table.
- When you click on “Export to Excel” button excel sheet will automatically download to your system.
- Open your excel file and match your records from excel sheet to HTML table, data will be same.
- Enjoy! have a great day.
Summary
I hope, this article would help you to understand about Import and Export data from Excel or HTML. In the end, You are expert in managing data from Excel sheet in MVC Application.
Источник
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.
posted 16 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
We have this requirement. In the HTML form, there will be rows of lines. Each line contains multiple Input(type=text) boxes. Basically, HTML form will look like EXCEL Grid, where each column or row is a series of INPUT boxes.
Now, users will copy data from any EXCEL column and will paste that data into any input box. Then, our application should copy the data from first cell of the EXCEL to that input box, the data from second(copied) cell to the input box below the first and so on. In brief, they want to cut/copy and paste from EXCEL column to HTML column.
I tried many many ideas/tricks but did not find any useful one. Any help?
Regards to all,
— Susanta
P.S. — We are not allowed to have ActiveX controls. Any IE scripting including javascript without ActiveX is allowed.
[ September 28, 2006: Message edited by: Susanta Chatterjee ]
posted 16 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
When you copy and paste an excel columns into the textbox, the columns are represented by tabs. So what I did was take the input, split it on the tabs and looped through the array and whamo.
Now if you want them to be able to post a bunch of rows at the same time and fill in a table. You can do it with a text area and splitting first on rn to get the rows and than on t to get the tabs.
Hope that helps you out a bit.
Eric
Susanta Chatterjee
Ranch Hand
Posts: 102
posted 16 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
Eric, Thanks for replying.
We tried your approach of splitting the data on newline separator and distributing in the cells below. But, to do this, we have to work with textarea (as you mentioned and input[type=text] cannot handle that).
But that poses additional problem for validation of data, as user now sees a different kind of control with scroll etc. Even though you can restrict the textarea by 1 row and specific size of column, there is an additional scrollbar on right and user can type beyond text area visible portiona and additional javascript validation for type of data etc., which does not fit users’ bill.
— Susanta
Eric Pascarello
author
Posts: 15385
posted 16 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
That is when: style=»overflow:hidden» comes in handy
Eric
Susanta Chatterjee
Ranch Hand
Posts: 102
posted 16 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
Eric,
Thanks. That works.
We successfully did a presentation to users using this technique and the HTML Grid design is a hit. Only trivial problem I found is that, in textarea, if you press enter then a new line is created in textarea (instead of form getting submitted as in case of input type=text box), as user may type something in those HTML grid.
I am thinking to put a javascript to check onkeypress to filter out Enter key. Do you think that to be a good approach for UI design? Or do you suggest some other technique.
— Susanta
[ September 29, 2006: Message edited by: Susanta Chatterjee ]
Eric Pascarello
author
Posts: 15385
posted 16 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
I actually did something like this in the past. I caught the enter key press, canceled it out, and had it execute the function to fill in the form.
Eric
In the previous post, I have explained how we can read csv file using javascript and HTML 5 filereader, now in this post, I have explained how we can use external library like xlsx to parse or read excel file using javascript and show it’s contents in HTML table. When file is uploaded using Javascript, it is read as Binary string initially, and then binary data is read using xlsx plugin.
Read XLSX using Javascript
Let’s beging by adding simple HTML file input and button to upload file
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="UploadProcess()" />
<br/>
<div id="ExcelTable"></div>
I have also included empty HTML div to create table inside it from our Excel file.
Now, we will create the function to upload the file and process the Excel file to get data from it and convert it into HTML table.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.5/xlsx.full.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.5/jszip.js"></script>
<script type="text/javascript">
function UploadProcess() {
//Reference the FileUpload element.
var fileUpload = document.getElementById("fileUpload");
//Validate whether File is valid Excel file.
var regex = /^([a-zA-Z0-9s_\.-:])+(.xls|.xlsx)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
//For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
GetTableFromExcel(e.target.result);
};
reader.readAsBinaryString(fileUpload.files[0]);
} else {
//For IE Browser.
reader.onload = function (e) {
var data = "";
var bytes = new Uint8Array(e.target.result);
for (var i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
GetTableFromExcel(data);
};
reader.readAsArrayBuffer(fileUpload.files[0]);
}
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid Excel file.");
}
};
function GetTableFromExcel(data) {
//Read the Excel File data in binary
var workbook = XLSX.read(data, {
type: 'binary'
});
//get the name of First Sheet.
var Sheet = workbook.SheetNames[0];
//Read all rows from First Sheet into an JSON array.
var excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[Sheet]);
//Create a HTML Table element.
var myTable = document.createElement("table");
myTable.border = "1";
//Add the header row.
var row = myTable.insertRow(-1);
//Add the header cells.
var headerCell = document.createElement("TH");
headerCell.innerHTML = "Id";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Name";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Country";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Age";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Date";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Gender";
row.appendChild(headerCell);
//Add the data rows from Excel file.
for (var i = 0; i < excelRows.length; i++) {
//Add the data row.
var row = myTable.insertRow(-1);
//Add the data cells.
var cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Id;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Name;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Country;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Age;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Date;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Gender;
}
var ExcelTable = document.getElementById("ExcelTable");
ExcelTable.innerHTML = "";
ExcelTable.appendChild(myTable);
};
</script>
In the above Javascript code, we are first adding references of XLSX plugin files and then adding two functions
- UploadProcess: Uploads the file on button click and convert it into Binary data, it also check if Browser is IE then process accordingly to convert file into binary.
- ProcessExcel: this function takes the binary data, reads the Sheet name, create Table element and append each row in it.
I have explained lines of code using Comment.
Suppose our sample Excel file looks like this
So, if use the above code in HTML/Javascript, output will be as below
Here is the fiddle link https://jsfiddle.net/abj98oxf/3/
Read XLS file using Javascript
In a Similar way, we can read .xls (excel) file also and show it in HTML table, I will repeat the same code, just few lines of code is different, also we will be using different plugin in it which is for .xls
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="UploadProcess()" />
<br/>
<div id="ExcelTable"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.5/jszip.js"></script>
<script type="text/javascript">
function UploadProcess() {
//Reference the FileUpload element.
var fileUpload = document.getElementById("fileUpload");
//Validate whether File is valid Excel file.
var regex = /^([a-zA-Z0-9s_\.-:])+(.xls|.xlsx)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
//For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
GetTableFromExcel(e.target.result);
};
reader.readAsBinaryString(fileUpload.files[0]);
} else {
//For IE Browser.
reader.onload = function (e) {
var data = "";
var bytes = new Uint8Array(e.target.result);
for (var i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
GetTableFromExcel(data);
};
reader.readAsArrayBuffer(fileUpload.files[0]);
}
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid Excel file.");
}
};
function GetTableFromExcel(data) {
//Read the Excel File data in binary
var cfb = XLS.CFB.read(data, {type: 'binary'});
var workbook = XLS.parse_xlscfb(cfb);
//get the name of First Sheet.
var Sheet = workbook.SheetNames[0];
//Read all rows from First Sheet into an JSON array.
var excelRows = XLS.utils.sheet_to_row_object_array(workbook.Sheets[Sheet]);
//Create a HTML Table element.
var myTable = document.createElement("table");
myTable.border = "1";
//Add the header row.
var row = myTable.insertRow(-1);
//Add the header cells.
var headerCell = document.createElement("TH");
headerCell.innerHTML = "Id";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Name";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Country";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Age";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Date";
row.appendChild(headerCell);
headerCell = document.createElement("TH");
headerCell.innerHTML = "Gender";
row.appendChild(headerCell);
//Add the data rows from Excel file.
for (var i = 0; i < excelRows.length; i++) {
//Add the data row.
var row = myTable.insertRow(-1);
//Add the data cells.
var cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Id;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Name;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Country;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Age;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Date;
cell = row.insertCell(-1);
cell.innerHTML = excelRows[i].Gender;
}
var ExcelTable = document.getElementById("ExcelTable");
ExcelTable.innerHTML = "";
ExcelTable.appendChild(myTable);
};
</script>
The XLS file upload code is the same as .XLSX one was, here are the changes
- We included difference JS plugin file : <script src=»https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js»></script>
- Changed a few lines of code for the function «GetTableFromExcel»
//Read the Excel File data in binary var cfb = XLS.CFB.read(data, {type: 'binary'}); var workbook = XLS.parse_xlscfb(cfb); //get the name of First Sheet. var Sheet = workbook.SheetNames[0]; //Read all rows from First Sheet into an JSON array. var excelRows = XLS.utils.sheet_to_row_object_array(workbook.Sheets[Sheet]);?
The rest of the code remains the same.
Here is the working fiddle link: https://jsfiddle.net/y3tx8wk4/1/
Note: You need to pass .xls file in this code to make it work.
Convert Excel to JSON using Javascript
You can also upload excel and then convert it to JSON data and proceed with it further.
<form enctype="multipart/form-data">
<input id="upload" type=file name="files[]">
</form>
<textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
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.parse(json_object));
jQuery('#xlx_json').val(json_object);
})
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
}
</script>
Here is the fiddle: https://jsfiddle.net/aszchkr0/ using which you can test the above code, just to search excel file and once value is changed you will find JSON result in textarea.
In the above code, we are reading excel using XLSX plugin, then we loop through each sheet and get XL row object and further convert it to JSON.
You may also like to read:
Read PDF file using Javascript
Convert Image to base64 string using Javascript
Convert seconds to hh:mm:ss using Javascript
Uncaught Error: «Cannot use import statement outside a module»
Encrypt and Decrypt string in Javascript
Email validation using jQuery (Various Methods)
Toggle Password input field using Javascript (Show/hide password)
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>