我使用以下JS代码在客户端过滤我的HTML表:
function searchAwards(){
var input, filter, table, tr, td, i;
input = document.getElementById("firstName");
filter = input.value.toUpperCase();
table = document.getElementById("award_entry");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
这很好用并适当过滤页面上的表格。我还实现了一些将HTML表导出为CSV的函数。执行此功能的代码是:
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
此代码将.csv文件发送到我的下载,但它始终显示表中的所有记录,而不管客户端上进行的过滤。有没有办法只将客户端上显示的过滤数据发送到CSV?
答案 0 :(得分:1)
确保未将隐藏/过滤的元素添加到csv结果中。 :)
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
// Don't add the row to the csv if it's hidden due to filtering.
if (rows[i].style.display === "none") continue;
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}