Sitemap
Your Blog Coach

Your Blog Coach

Elevate skills with tutorials, dive into unique programming guidance. Every code line is a step toward success. 🚀 #YourCodingJourney

Export HTML Table to Excel Using JavaScript

2 min readOct 13, 2022

--

There are many libraries that you can use to convert your HTML table data into excel (XLSX or XLS) file.

Export Using TabletoExcel Library

The TabletoExcel library is very simple and easy to use. You can export your HTML table to valid excel file effortlessly.

Get Your Blog Coach’s stories in your inbox

Join Medium for free to get updates from this writer.

You just have to embed this library in your page where the HTML table shows that you want to convert it into an excel file.

<table id="top-students">
<tr>
<th>Name</th>
<th>Class</th>
<th>Roll No</th>
<th>Section</th>
</tr>
<tr>
<td>Robert Sen</td>
<td>12th</td>
<td>34</td>
<td>A</td>
</tr>
<tr>
<td>Vicky Thakur</td>
<td>10th</td>
<td>13</td>
<td>C</td>
</tr>
<tr>
<td>Ribika Mattu</td>
<td>11th</td>
<td>16</td>
<td>D</td>
</tr>
<tr>
<td>Simran Singh</td>
<td>9th</td>
<td>26</td>
<td>A</td>
</tr>
</table>
<button id="exportBtn" onclick="topStudents_xlsx(this)">Export XLSX</button>

Now just add the following script tag for the TabletoExcel library to your page’s footer. You can also add a CDN link.

<script type="text/javascript" src="../dist/tableToExcel.js"></script>

Now write a javascript code using the library function to export the HTML table to an excel file in XLSX or XLS format.

<script>
function topStudents_xlsx() {
TableToExcel.convert(document.getElementById("top-students"), {
name: "top-students.xlsx",
sheet: {
name: "Marks Sheet"
}
});
}
</script>

Export File without Library

Let’s see how to export the HTML table to excel without any third-party library and only with pure javascript.

<script>
function topStudents_sheet(){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableContent = document.getElementById("top-students-sheet");
var tableHTMLdata = tableContent[0];

// File name
var filename = 'top-students-sheet.xls';

// Make download link element
downloadLink = document.createElement("a");

document.body.appendChild(downloadLink);

if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTMLdata], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
} else{
downloadLink.href = 'data:' + dataType + ', ' + tableHTMLdata;
downloadLink.download = filename;

//triggering the function
downloadLink.click();
}
}
</script>

Now you can run this function on click event to targetting to table. So simply add the button to your page and add the click event for it as follows.

<button onclick="topStudents_sheet()">Export XLS</button>

Hope it is helpful for you.

--

--

Your Blog Coach
Your Blog Coach

Written by Your Blog Coach

Elevate skills with tutorials, dive into unique programming guidance. Every code line is a step toward success. 🚀 #YourCodingJourney