首页 > 解决方案 > Javascript 将数据表导出到 csv 但想要包含表头并排除三列

问题描述

尝试将数据表 HTML 表导出到 CSV,我已经使用 Javascript 实现了一些代码,但这不包括我想要添加的列标题。此外,我想从导出中排除特定列,但不确定如何调整当前我工作的代码:

创建了一个 JS FIDDLE 示例,其中 CSV 不包含标题并希望在导出时隐藏“Office”和“Age”列:https ://jsfiddle.net/matp4bjn/

function download_csv_normal(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;

    // We have to create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Make sure that the link is not displayed
    downloadLink.style.display = "none";

    // Add the link to your DOM
    document.body.appendChild(downloadLink);

    // Lanzamos
    downloadLink.click();
}

function export_table_to_csv_normal(html, filename) {
    var csv = [];
    //var rows = document.querySelectorAll(".vs tr"); //gets paginated version
    var rows = $("#tabledt").dataTable().fnGetNodes(); //gets all rows
    //var rows = document.querySelectorAll("tabledt 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
    download_csv_normal(csv.join("\n"), filename);
}


function pad2(n) { return n < 10 ? '0' + n : n }


document.querySelector(".savebtn").addEventListener("click", function () {
    var html = document.querySelector(".vs").outerHTML;
    var date = new Date();
    var file = "vstable_" + date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2(date.getDate()) + pad2(date.getHours()) + pad2(date.getMinutes()) + pad2(date.getSeconds()) + ".csv";
    export_table_to_csv_normal(html, file);
});

HTML:

  <button class="savebtn">
SAVE
</button>

标签: javascripthtmlasp.netdatatable

解决方案


您的代码工作正常,只需要插入标题并实现列的条件以跳过列,您已使列不显示,但仍存在于代码中,尽管在屏幕上不可见,这就是它们打印的原因.csv。在 for 循环中,您需要跳过它们。

解决您的问题

for (var i = 0; i < rows.length; i++) {
    
    //only run for the first iteration to set header row in the csv
    if(i==0){
        var row2 = [], cols2 = $('#tabledt thead tr')[0];
        for(var i2 = 0; i2 < cols2['cells'].length; i2++){
            //skip office and age columns
            if(i2==2 || i2==3){continue;}
            
            //add columns
            row2.push(cols2['cells'][i2].innerText);
            //console.log(cols2['cells'][i2].innerText);
        }
        //insert header
        csv.push(row2.join(","));
    }        
        
    var row = [], cols = rows[i].querySelectorAll("td");
    
    for (var j = 0; j < cols.length; j++){
        //skip office and age columns
        if(j==2 || j==3){continue;}

        //add columns
        row.push(cols[j].innerText);
    }

    csv.push(row.join(","));
}

// Download CSV
download_csv_normal(csv.join("\n"), filename)

推荐阅读