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>
<html>
<head>
  <title>how to convert table to CSV file</title>
</head>
<body>
      <table style="width:100% "id="id1">


 <tbody>
  <tr>
    <td>Product</td>
    <td>Price</td>
  </tr>
    <tr>

     <td>orange</td>
     <td>#210</td>
    </tr>


    <tr>

      <td>apple</td>
      <td>#400</td>
    </tr>

    </tbody>

</table>

<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 + `"`);
                    }
                    csv.push(row.join(separator));
                }
                var csv_string = csv.join("\n");
                // Download it
                var filename = "export_" + table_id + "_" + new Date().toLocaleDateString() + ".csv";
                var link = document.createElement("a");
                link.style.display = "none";
                link.setAttribute("target", "_blank");
                link.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURIComponent(csv_string));
                link.setAttribute("download", filename);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }

             </script>
</body >
</html>
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)