DEV Community

Cover image for How to convert html table to CSV file
popoola Temitope
popoola Temitope

Posted on • Updated on

How to convert html table to CSV file

To convert a table to csv file you have to create html table and then give the table tag an id for referencing the table.

<!DOCTYPE html>
  <title>how to convert table to CSV file</title>
      <table style="width:100% "id="id1">







<button onclick="download_table_as_csv();">Convert To CSV File</button>

Enter fullscreen mode Exit fullscreen mode

now we'll now create js code that will convert the table to csv file

<script >
              function download_table_as_csv(table_id="id1", separator = ",") {
                // Select rows from table_id
                var rows = document.querySelectorAll("table#" + table_id + " tr");
                // Construct csv
                var csv = [];
                  //looping through the table
                for (var i = 0; i < rows.length; i++) {
                    var row = [], cols = rows[i].querySelectorAll("td, th");
                       //looping through the tr
                    for (var j = 0; j < cols.length; j++) {
                       // removing space from the data
                        var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, "").replace(/(\s\s)/gm, " ")
                         // removing double qoute from the data
                        data = data.replace(/"/g, `""`);
                        // Push escaped string
                        row.push(`"` + data + `"`);
                var csv_string = csv.join("\n");
                // Download it
                var filename = "export_" + table_id + "_" + new Date().toLocaleDateString() + ".csv";
                var link = document.createElement("a");
       = "none";
                link.setAttribute("target", "_blank");
                link.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURIComponent(csv_string));
                link.setAttribute("download", filename);

</body >
Enter fullscreen mode Exit fullscreen mode

when you click on the Convert To CSV File button the table will convert to csv file

Am always ready to learn, for any addition feel-free to comment

Top comments (0)