Export table to a csv file, and download it Follow
Sometimes you want to download the data that is in a table in the HTML page to a csv (exel) file.
It is possible in a few simple steps:
1. add a button that will call custom function: exportToCsv.
in the Javascript paste the following code:
function exportToCsv() {
//extract headers
let headers = [];
$('#tableOutputHead tr th').each(
function (i, thElem){
headers.push('"' + thElem.innerText + '"')
})
//extract rows
let cols = [];
let rows = [];
$('#tableOutputBody tr').each(
function(t, elem){
cols = [];
$(elem).find('td').each(
function(i, tdElem){
cols.push(tdElem.innerText);
})
rows.push('"'+cols.join('","')+'"');
})
//combine all
const result = headers.join(',') + '\r\n' + rows.join('\r\n');
let csvContent = "data:text/csv;charset=utf-8,";
// adding a BOM prefix (\uFEFF) to the beginning of the file
//(https://stackoverflow.com/questions/155097/microsoft-excel-mangles-diacritics-in-csv-files)
csvContent += '\ufeff' + result;
var encodedUri = encodeURI(csvContent);
//creating the link
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "exportTable.csv");
link.innerHTML= "Click Here to download";
document.body.appendChild(link); // Required for FF
link.click();
}
Comments
0 comments
Please sign in to leave a comment.