I have a tricky dynamic table built from a model that I did not want to fashion in the controller so wanted to just download the table as shown.
This Jquery/Javascript solution allowed me to do just that.
Using a button on the page id='export' and using a table on the page id='tblExport'
We add an event listener for the button - I have declared everything explicitly but could probably have shortened some references to objects.
//For the Csv Export
const toCsv = function (table) {
// Query all rows
var data = "";
var tableData = [];
var rows = $("table tr");
rows.each(function (index, row) {
var rowData = [];
$(row).find("th, td").each(function (index, column) {
rowData.push(column.innerText);
});
tableData.push(rowData.join(","));
});
data += tableData.join("\n");
return data;
};
const download = function (text, fileName) {
const link = document.createElement('a');
link.setAttribute('href', `data:text/csv;charset=utf-8,${encodeURIComponent(text)}`);
link.setAttribute('download', fileName);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const table = document.getElementById('tblExport');
const exportBtn = document.getElementById('export');
exportBtn.addEventListener('click', function () {
// Export to csv
const csv = toCsv(table);
var reportName = $("#ReportName").val();
var repDate = $("#RepTitle").text().replaceAll(" ","_");
// Download it
download(csv, `${reportName}_${repDate}.csv`);
});
Comments