在客户端上过滤HTML表,但导出到CSV显示整个表



我使用以下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?

确保未将隐藏/过滤的元素添加到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);
}

最新更新