Export table data to Excel using jQuery
MIMEtype: Optional. The type of document you are writing to. Default value is "text/html".
replace: Optional. If set, the history entry for the new document inherits the history entry from the document which opened this document.
HTML
<div class="card border-primary mb-3">
<table class="table table-hover results" id="exportExcel">
<thead style="color: white; background-color: #0099CC">
<tr>
<td>Číslo</td>
<td>Meno</td>
<td>Priezvisko</td>
<td>Ostatné</td>
<td class="stockItem"><button type="button" id="excel" class="btn btn-sm btn-outline-light">stiahni zoznam</button></td>
</tr>
</thead>
<tbody id="excelExport"></tbody>
<!-- data dynamically loaded with ajax -->
<tr>
<td>1</td>
<td>Ľudmila</td>
<td>Malá</td>
<td>LM</td>
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>Hraško</td>
<td>PH</td>
</tr>
</table>
</div>
CSS
body {
font-size: 12pt;
font-family: Calibri;
padding : 10px;
}
table {
border: 1px solid black;
}
th {
border: 1px solid black;
padding: 5px;
background-color:grey;
color: white;
}
td {
border: 1px solid black;
padding: 5px;
}
JavaScript
$(document).ready(function() {
$("#excel").click(function(e) {
// ajax field needed
/*var stDate = $("#fromDate").val();
var enDate = $("#toDate").val();*/
//ajax function
/*
$.ajax({
type: 'POST',
url: 'downloadExcel.php',
data: 'startDate='+stDate+'&endDate='+enDate,
success: function(data) {
$('#excelExport').html(data);*/
e.preventDefault();
//getting data from our table
var data_type = 'data:application/vnd.ms-excel; charset=utf-8';
var table_div = document.getElementById('exportExcel');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
var a = document.createElement('a');
a.href = data_type + ', ' + table_html;
a.download = 'exported_table' + '.xls';
a.click();
//}
//});
});
});