Assume that we have a table element and a button for exporting the table cells to CSV as following:
<table id="exportMe" class="table">
...
</table>
<button id="export">Export</button>
Export the table cells to CSV
The function below exports all the cells of
table to CSV format. First, we
select all the rows,
loop over them and export each row to CSV.
In each row, we go through all cells, and retrive their
text content.
const toCsv = function (table) {
const rows = table.querySelectorAll('tr');
return [].slice
.call(rows)
.map(function (row) {
const cells = row.querySelectorAll('th,td');
return [].slice
.call(cells)
.map(function (cell) {
return cell.textContent;
})
.join(',');
})
.join('\n');
};
Download the CSV
The function below creates a fake
a element whose content is
text and triggers the
click event.
For more information, you can visit the
Download a file post.
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);
};
The last thing is to connect all pieces together. We just need to
handle the
click event of the
Export button:
const table = document.getElementById('exportMe');
const exportBtn = document.getElementById('export');
exportBtn.addEventListener('click', function () {
const csv = toCsv(table);
download(csv, 'download.csv');
});
Demo
See also