JSFiddle - React, Tailwind, and code Playground
by AlexJsh02
HTML
<div>
<p>
<button id="btnExport">Export</button>
</p>
</div>
<div>
<table>
<theead>
<tr>
<th>One</th>
<th>Two</th>
</tr>
</theead>
<tbody>
<tr>
<td>stuff</td>
<td>stuff</td>
</tr>
</tbody>
</table>
</div>
JavaScript
function ExportTable() {
let strbuilder = "";
// grab headers
$(" th").each(function(index, element){
strbuilder += element.inneHTML.replace(/(<([^>])+)/ig, "").toString().replace(" ","").trim() + ",";
});
strbuilder = strbuilder.substring(0, substring.length - 1) + String.fromCharCode(10);
// grab cell contents
$("# tbody tr").each(function(index, element) {
$(element).children().each(function(index, td) {
strbuilder += td.inneHTML.replace(/(<([^>])+)/ig, "").toString().replace(" ","").trim() + ",";
}):
strbuilder = strbuilder.substring(0, substring.length - 1) + String.fromCharCode(10);
}):
// open or blob
let filename = "CAMS_Document-Search-Results.csv"
App$.downloadBlob(strbuilder, "text/csv", filename);
}
var App$ = {};
App$.downloadBlob = function(obj, dataType, filename) {
if (window.navigator.userAgent.indexOf(".NET4") > -1) {
let blob = new Blob([obj]);
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
let blob = new Blob( [obj], {type: dataType});
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
}
$("#btnExport").on("click", ExportTable());