<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content=
"
width
=
device
-width,
initial-scale
=
1
.0">
<
title
>Table to Excel</
title
>
<
script
src
=
</
script
>
<
style
>
#dwnldBtn{
background-color: green;
color: #fff;
padding: 10px;
border: none;
border-radius: 5px;
margin: 2rem 0;
cursor: pointer;
}
</
style
>
</
head
>
<
body
>
<
center
>
<
table
id
=
"dataTable"
border
=
"1"
>
<
thead
>
<
tr
>
<
th
>ID</
th
>
<
th
>Name</
th
>
<
th
>Email</
th
>
<
th
>Phone</
th
>
</
tr
>
</
thead
>
<
tbody
>
<
tr
>
<
td
>12345</
td
>
<
td
>Samyuj Kumar</
td
>
<
td
>samyuj@example.com</
td
>
<
td
>123-456-7890</
td
>
</
tr
>
<
tr
>
<
td
>12346</
td
>
<
td
>Sanjay Dhillon</
td
>
<
td
>SDhillon@example.com</
td
>
<
td
>012-345-6789</
td
>
</
tr
>
<
tr
>
<
td
>12347</
td
>
<
td
>Johan Greg</
td
>
<
td
>gregJo@example.com</
td
>
<
td
>987-654-3210</
td
>
</
tr
>
</
tbody
>
</
table
>
<
button
id
=
"dwnldBtn"
>
Download Excel Sheet
</
button
>
</
center
>
<
script
>
$(document).ready(function () {
$('#dwnldBtn').on('click', function () {
downloadExcelTable('dataTable', 'employeeData');
});
function downloadExcelTable(tableID, filename = '') {
const linkToDownloadFile = document.
createElement("a");
const fileType = 'application/vnd.ms-excel';
const selectedTable = document.
getElementById(tableID);
const selectedTableHTML = selectedTable.outerHTML.
replace(/ /g, '%20');
filename = filename ? filename + '.xls' :
'excel_data.xls';
document.body.appendChild(linkToDownloadFile);
if (navigator.msSaveOrOpenBlob) {
const myBlob = new Blob(['\ufeff',
selectedTableHTML], {
type: fileType
});
navigator.msSaveOrOpenBlob(myBlob, filename);
} else {
// Create a link to download
// the excel the file
linkToDownloadFile.href = 'data:' + fileType +
', ' + selectedTableHTML;
// Setting the name of
// the downloaded file
linkToDownloadFile.download = filename;
// Clicking the download link
// on click to the button
linkToDownloadFile.click();
}
}
});
</
script
>
</
body
>
</
html
>