Create CSV file using Jquery/ JavaScript


Below is sample Html and Jquery to create CSV using Jquery or Javascript.

if have issue in generating data containing comma (,) use below code.


<table id="tableId">

    <thead>

        <tr><th>Heading</th><th>Heading</th></tr>

    </thead>

    <tbody>

        <tr><td>cell</td><td>cell2</td></tr>

    </tbody>

</table>

<input type="button" value="select table" onclick="
createCSVFile(document.getElementById('tableId') );">
<script> function createCSVFile(tablehtml) { export_table_to_csv(tablehtml,'report.csv'); } function download_csv(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(html, filename) { var csv = []; var doc = document.implementation.createHTMLDocument("New Document"); var p = doc.createElement("p"); p.innerHTML = html; doc.body.appendChild(p); var rows = doc.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++) { //check if data contains comma if(cols[j].innerText.trim().includes(',')){ row.push('"'+cols[j].innerText.trim() +'"'); } else{ row.push(cols[j].innerText.trim()); } } csv.push(row.join(",")); } // Download CSV download_csv(csv.join("\n"), filename); } </script>
Thanks for visiting.

If have any doubt or suggestions please comment.

Have happy coding. :) !!!!!!!

3 comments:

  1. this is really nice to read..informative post is very good to read..thanks a lot! python代写

    ReplyDelete
  2. .my-assignmentexpertR语言代写my-assignmentexpert
    机器学习代写

    ReplyDelete
  3. 市场营销作业代写.my-assignmentexpertmatlab代写my-assignmentexpert

    ReplyDelete