Reputation: 1202
I have a page on which I have multiple html tables. I want to download all the tables into one CSV or Excel file using JS or JQuery..I searched for it and found some jQuery plugins which do that
https://www.jqueryscript.net/table/Table-To-CSV-jQuery-csvExport.html
but the issue is that they are only working for one table on the page.I want to save all the tables on the page in one excel sheet. Has anybody had any luck with exporting multiple html tables on a page into one excel file which works in IE also.
Thanks
Upvotes: 0
Views: 1875
Reputation: 6745
It looks like we need to use a BLOB for Edge/IE (based on this related answer). Give this a shot. I tested it in Edge and it seems to work.
NOTE: You won't be able to click the "Export" button in the snippet below because the code is in a sandboxed environment. I created a fiddle for you to test it at here: https://jsfiddle.net/ratk2pmz/
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
}
return function(table, name) {
if (!table.nodeType)
table = document.getElementById(table)
var ctx = {
worksheet: name || 'Worksheet',
table: table.innerHTML
}
var HeaderName = 'Download-ExcelFile';
var ua = window.navigator.userAgent;
var msieEdge = ua.indexOf("Edge");
var msie = ua.indexOf("MSIE ");
if (msieEdge > 0 || msie > 0) {
if (window.navigator.msSaveBlob) {
var dataContent = new Blob([base64(format(template, ctx))], {
type: "application/csv;charset=utf-8;"
});
var fileName = "excel.xls";
navigator.msSaveBlob(dataContent, fileName);
}
return;
}
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(format(template, ctx)));
}
})()
<table id="table">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
<button onclick="tableToExcel('table', 'SHEET1')" class="btn btn-primary">Export to Excel</button>
Upvotes: 1