Assume, Im having a table like below:
I need to drop the "Contact" column and export the remaining column to the CSV file.
HTML:
<button id="downl" onclick="dropColumn('mytableid');">Download</button>
On click of the download button, js function will get called.
JavaScript
//Drop Column
function dropColumn(mytableid){
var clonetable = $('#mytableid').clone();
clonetable.find('td:nth-child(2),(the:nth-child(2)').remove();
download_table_as_csv(clonetable);
}
//Download as CSV
function download_table_as_csv(table_id, separator = ',') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Error:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'table#[object Object]tr' is not a valid selector.
How to export table data to CSV by excluding a specific column?.Any way to achieve this.
Thanks.