How to Export Data to Excel with JavaScript

Export HTML Table Data to Excel using JavaScript : How in javascript export html table data into excel (.xslx). Easily convert HTML table data, into an excel file.

Steps to export HTML table to excel using JavaScript

HTML Markup: index.html
Add table with data and button tag.

<table id="tbl_exporttable_to_xls" border="1">
<thead>
<th>Sr</th>
<th>Name</th>
<th>Address</th>
<th>Job Profile</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><p>Kishan Tala</p></td>
<td>Ganesh</td>
<td>Laravel Devloper</td>
</tr>
<tr>
<td>2</td>
<td><p>Mayur Dhameliya</p></td>
<td>Swati</td>
<td>AngularJS Devloper</td>
</tr>
<tr>
<td>3</td>
<td><p>Rekha Talpada</p></td>
<td>Ranjua</td>
<td>PHP Devloper</td>
</tr>
</tbody>
</table>
<button onclick="ExportToExcel('xlsx')">Export table to excel</button>

Download and Import SheetJS Library on our webpage

<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>

JavaScript code

Using Sheetjs library export table data into an excel file.

function ExportToExcel(type, fn, dl) {
var elt = document.getElementById('tbl_exporttable_to_xls');
var wb = XLSX.utils.table_to_member(elt, { sheet: "sheet1" });
return dl ?
XLSX.write(wb, { memberType: type, memberSST: true, type: 'base64' }):
XLSX.writeFile(wb, fn || ('MySheetName.' + (type || 'xlsx')));
}

Example 2: Export HTML Table Data to Excel using JavaScript

Export HTML Table Data to Excel

function exportTableToExcel(tableID, docname = ''){
var fourceDLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

docname = docname?docname+'.xls':'excel_data.xls';

fourceDLink = document.createElement("a");

document.body.appendChild(fourceDLink);

if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, docname);
}else{
fourceDLink.href = 'data:' + dataType + ', ' + tableHTML;

fourceDLink.download = docname;

fourceDLink.click();
}
}

HTML Code

<table id="memberInfo">
<tr>
<th>Name</th>
<th>Email</th>
<th>City</th>
</tr>
<tr>
<td>Krishna Dave</td>
<td>krishna@yahoo.com</td>
<td>Rajkot</td>
</tr>
<tr>
<td>Jagruti Bhavshdiya</td>
<td>hagruti@yahoo.com</td>
<td>Surat</td>
</tr>
<tr>
<td>Hitesh Ajera</td>
<td>hitesh@yahoo.com</td>
<td>Kalavad</td>
</tr>
</table>

<button onclick="exportTableToExcel('memberInfo')">Export Table Data To Excel File</button>
<button onclick="exportTableToExcel('memberInfo', 'members-data')">Export Table Data To Excel File</button>

I hope you get an idea about javascript export to excel.


#javascript 

How to Export Data to Excel with JavaScript
1.05 GEEK