Exporting HTML Table to Excel [.xls, .csv] using JavaScript Tutorial
In this tutorial, you will learn how to Export HTML Table Data to Excel Spreadsheets and CSV Files using JavaScript. This tutorial aims to provide the IT/CS student and new programmers with a reference to learn to export Data into Excel using only Pure JavaScript. Here, I will provide sample snippets on how to achieve this tutorial's objectives. A working sample program source code zip file is also provided and is free to download.
In some programs or web applications, the management often requires an export of data from the system to excel spreadsheets or CSV files. Mostly, the purpose of this feature is to extract the data that allows the system management to use it for some other purpose. Export to Excel features is commonly implemented along with the report feature of the program.
How to Export HTML Table to Excel File using JS?
There are a lot of ways to Export Table Data to CSV or Excel Spreadsheet. Some developers preferred to use free plugins or libraries to make it possible. Using JavaScript built-in methods and short lines of script, we can also achieve the said feature for our web application. JavaScript comes with a Blob object which is very helpful to achieve our goal here. We can simply generate a file-like raw data of the HTML Table and create an object URL to put in an anchor tag which enables us to download the file.
What is JS Blob?
A blob is an immutable, file-like object with raw data; it can be read as text or binary data or turned into a ReadableStream so that its methods can be used to process the data. The JavaScript's Blob object represents blobs.
Steps of Exporting Table Data to Excel [.xls, .csv]?
Export as Excel Spreadsheet File
- Get the Table outer HTML in JS and put it into a new HTML document string
- Convert the HTML document string into a Blob object using the application/vnd.openxmlformats-officedocument.spreadsheetml.sheet content-type.
- Create an Anchor Element
- Set a download attribute to the anchor with the filename as the value i.e exportedData.xls
- Create an Object URL of the Blob object and set it into the anchor's href attribute
- Append the Anchor Tag to the page document body
- Trigger Click the Anchor Tag to download the exported file
Export as CSV File
- Get the Table outer HTML in JS and put it into a new HTML document string
- Convert the HTML document string into a Blob object using the text/csv content type.
- Create an Anchor Element
- Set a download attribute to the anchor with the filename as the value i.e exportedData.csv
- Create an Object URL of the Blob object and set it into the anchor's href attribute
- Append the Anchor Tag to the page document body
- Trigger Click the Anchor Tag to download the exported file
Snippets
Using the following snippet, we can export the Table Data into a (.xls) or Excel Spreadsheet File easily. The following script uses the Blob object to convert HTML into a blob using the application/vnd.openxmlformats-officedocument.spreadsheetml.sheet content type.
- document.getElementById("exportTable").addEventListener("click", function(e){
- e.preventDefault()
- var _tbl = document.getElementById('exampleTbl').outerHTML
- var excel_content = `<html><body>${_tbl}</body></html>`
- var file = new Blob([excel_content], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
- var dl_anchor = document.createElement('a')
- dl_anchor.style.display = this.nonce;
- dl_anchor.download = "tableData.xls";
- dl_anchor.href = window.URL.createObjectURL(file);
- document.body.appendChild(dl_anchor)
- dl_anchor.click()
- })
The following snippet has a similarity to the first snippet I provided. The only difference is that the table data was extracted from the table cells. The table rows are separated with (\r\n) or next line delimiter and each cell of the row is separated using the comma (,). Aside from that, the Blob content type must be text/csv.
- document.getElementById("exportTableCSV").addEventListener("click", function(e){
- e.preventDefault()
- var _tbl_rows = document.querySelectorAll('#exampleTbl tr')
- var csv ="";
- var rows = []
- _tbl_rows.forEach(el => {
- var row = []
- el.querySelectorAll('th, td').forEach(ele => {
- var ele_clone = ele.cloneNode(true)
- ele_clone.innerText = (ele_clone.innerText).replace(/\"/gi, '\"\"')
- ele_clone.innerText = ('"' + ele_clone.innerText + '"')
- row.push(ele_clone.innerText)
- })
- rows.push(row.join(","));
- })
- csv += rows.join(`\r\n`)
- var file = new Blob([csv], {type:'text/csv'});
- var dl_anchor = document.createElement('a')
- dl_anchor.style.display = this.nonce;
- dl_anchor.download = "tableCsv.csv";
- dl_anchor.href = window.URL.createObjectURL(file);
- document.body.appendChild(dl_anchor)
- dl_anchor.click()
- })
Using the JavaScript snippets that I provided above, we can achieve our goal and objective of this tutorial which is to export Table Data to an Excel Spreadsheet and CSV File. The following is the snippet of a simple program that demonstrates the usage of the given snippet above.
Example
Interface
Assuming that we have an application page with an HTML Table that displays a list of record. Here's an example script of an application page interface. The script is known as an index.html file.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- <style>
- html, body{
- height: 100%;
- width: 100%;
- }
- body{
- display: flex;
- height: 100%;
- width: 100%;
- flex-direction: column;
- }
- body>nav, body>footer{
- flex-shrink: 1;
- }
- body>main{
- flex-shrink: 1;
- flex-grow: 1;
- overflow: auto;
- margin: 1em 0;
- }
- pre{
- min-height:20vh
- }
- </style>
- </head>
- <body style="background:#eff3fc">
- <nav class="navbar navbar-expand-lg navbar-dark" style="background:#495C83">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <main class="container-fluid">
- <div class="col-lg-10 col-md-11 col-sm-12 col-xs-12 mx-auto">
- <hr>
- <div class="card mt-3 rounded-0">
- <div class="card-header">
- <div class="d-flex justify-content-between align-items-end">
- <div class="col-auto flex-shrink-1 flex-grow-1">
- </div>
- <div class="col-auto flex-shrink-1">
- </div>
- </div>
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <div class="table-responsive">
- <table class="table table-hover table-striped table-bordered" id="exampleTbl">
- <thead>
- <tr class="bg-gradient bg-primary text-light">
- </tr>
- </thead>
- <tbody>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </div>
- </div>
- </main>
- <footer class="container-fluid py-3" style="background:#495C83; color:#fff">
- <div class="container-fluid my-2">
- <div class="text-center">
- </div>
- </div>
- </footer>
- </body>
- </html>
JavaScript
Next, is creating the JavaScript file that contains the script for exporting the table data to .xls and .csv files. This file is loaded at the index.html file and is known as script.js.
- /**
- * Exporting Table Data into Excel
- */
- document.getElementById("exportTable").addEventListener("click", function(e){
- e.preventDefault()
- var _tbl = document.getElementById('exampleTbl').outerHTML
- var excel_content = `<html><body>${_tbl}</body></html>`
- var file = new Blob([excel_content], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
- var dl_anchor = document.createElement('a')
- dl_anchor.style.display = this.nonce;
- dl_anchor.download = "tableData.xls";
- dl_anchor.href = window.URL.createObjectURL(file);
- document.body.appendChild(dl_anchor)
- dl_anchor.click()
- })
- /**
- * Exporting Table Data into CSV
- */
- document.getElementById("exportTableCSV").addEventListener("click", function(e){
- e.preventDefault()
- var _tbl_rows = document.querySelectorAll('#exampleTbl tr')
- var csv ="";
- var rows = []
- _tbl_rows.forEach(el => {
- var row = []
- el.querySelectorAll('th, td').forEach(ele => {
- var ele_clone = ele.cloneNode(true)
- ele_clone.innerText = (ele_clone.innerText).replace(/\"/gi, '\"\"')
- ele_clone.innerText = ('"' + ele_clone.innerText + '"')
- row.push(ele_clone.innerText)
- })
- rows.push(row.join(","));
- })
- csv += rows.join(`\r\n`)
- var file = new Blob([csv], {type:'text/csv'});
- var dl_anchor = document.createElement('a')
- dl_anchor.style.display = this.nonce;
- dl_anchor.download = "tableCsv.csv";
- dl_anchor.href = window.URL.createObjectURL(file);
- document.body.appendChild(dl_anchor)
- dl_anchor.click()
- })
Snapshots
Here are the snapshots of the result of the program source code I provided above.
Page Interface
Exported Excel Spreadsheet
Exported CSV File
There you go! You can now test the sample program on your end and see if it works properly. I provided also the complete source code file of the sample program that I created for this tutorial. You can download it by clicking the download button below this article.
That's it! That's the end of this tutorial. I hope this Exporting HTML Table to Excel Spreadsheet and CSV File using JavaScript Tutorial will help you with what you are looking for and you'll find this useful for your current and future projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Comments
Add new comment
- Add new comment
- 1823 views