Javascript exporting datatable to csv but want to include table headers and exclude three columns

Trying to export a datatable HTML table to CSV which I have implemented some code using Javascript but this doesnt include my column headers which I want to add in. Also I want to exclude a particular column from the export but not sure how to tweak the current code I have working:

Created a JS FIDDLE with an example where the CSV is not including headers and want to hide the column ‘Office’ and ‘Age’ on export: 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>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Your code was working fine just needed to insert the header and implement condition for the columns to skip columns, you have made the columns to display none but that were still present in the code although not visible on the screen, that’s why they were printing in the csv. In for loop you need to skip them.

Solution to your problem

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)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x