Export a HTML table as a CSV file on the front end

This demo shows how to add a ‘Download to CSV’ button to your Formidable Views and allow users to download a CSV file of any table content from the front end. This was adapted from an original article on CodexWorld.

NameEmailCountry
John Doejohn@gmail.comUSA
Stephen Thomasstephen@gmail.comUK
Natly Oathnatly@gmail.comFrance

The Code

<table>
  <tr>
    <th>Name</th>
    <th>Email</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>John Doe</td>
    <td>john@gmail.com</td>
    <td>USA</td>
  </tr>
  <tr>
    <td>Stephen Thomas</td>
    <td>stephen@gmail.com</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Natly Oath</td>
    <td>natly@gmail.com</td>
    <td>France</td>
  </tr>
</table>

This is some basic html for a table. If you are using Formidable Forms you can use a View to create your table. If you need assistance creating a table of your entires using a view you can follow the guide HERE.

<button onclick="exportTableToCSV('members.csv')">Export HTML Table To CSV File</button>

This is the button html. if you are using a view to create your table this can be placed in the ‘After Content’ section of the view or alternativly anywhere else on the page.

The following JavaScript code contains 2 functions, named downloadCSV() and exportTableToCSV(). The downloadCSV() function takes CSV data and generates a download link to download the HTML table data into a CSV file.

function exportTableToCSV(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 file
    downloadCSV(csv.join("\n"), filename);
}

The exportTableToCSV() function creates a CSV data from an HTML table and downloads CSV data as a file by using the downloadCSV() function.

function downloadCSV(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;

    // Create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Hide download link
    downloadLink.style.display = "none";

    // Add the link to DOM
    document.body.appendChild(downloadLink);

    // Click download link
    downloadLink.click();
}

You can either add this JS directly to the ‘Before Content’ section of your view (wrapped in < script > tags or create a new file (save it as ‘table-export.js‘) and load it in remotely by adding the following code to the ‘Before Content’ section of your view (or anywhere else on the page).

<script src="https://www.YourSite.com/wp-content/JS/table-export.js"></script>