【发布时间】:2023-03-03 02:28:02
【问题描述】:
我需要删除“联系人”列并将剩余的列导出到 CSV 文件。
HTML:
<button id="downl" onclick="dropColumn('mytableid');">Download</button>
点击下载按钮,会调用js函数。
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);
}
错误:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'table#[object Object]tr' is not a valid selector.
如何通过排除特定列将表数据导出到 CSV?。任何方式来实现这一点。
谢谢。
【问题讨论】:
-
你能添加构成表格的实际 HTML 或者至少是它的渲染版本吗?
标签: javascript html html-table jquery-selectors export-to-csv