Skip to main content

Export html table to csv using javascript

<table>
    <tr><th>Name</th><th>Age</th><th>Country</th></tr>
    <tr><td>MANOJ</td><td>26</td><td>INDIA</td></tr>
    <tr><td>KRISHAN</td><td>19</td><td>INDIA</td></tr>
    <tr><td>SUSHEEL</td><td>32</td><td>INDIA</td></tr>
</table>
<button onclick="Export_CSV ()">Export HTML table to CSV file</button>

function download_csv(csv, filename) {
    var csvFile;
    var downloadLink;

    csvFile = new Blob([csv], {type: "text/csv"});
    downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}

function export_table_to_csv(html, 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
    download_csv(csv.join("\n"), filename);
}

function Export_CSV {
    var html = document.querySelector("table").outerHTML;
    export_table_to_csv(html, "table.csv");
}

Comments

Popular posts from this blog

Asp.net Component Model

ASP.Net Component Model: The ASP.Net component model provides various building blocks of ASP.Net pages. Basically it is an object model, which describes: ·          Server side counterparts of almost all HTML elements or tags, like <form> and <input>. ·          Server controls, which help in developing complex user-interface for example the Calendar control or the Gridview control. ASP.Net is a technology, which works on the .Net framework that contains all web-related functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.Net web application is made of pages. When a user requests an ASP.Net page, the IIS delegates the processing of the page to the ASP.Net runtime system. The ASP.Net runtime transforms the .aspx page into an instance of a class, which inherits from the base class Page of the .Net framework. Therefore, each ASP.Net page is an object and a...