Export HTML table to CSV file

html-table-to-csv

Imagine you have an HTML table, for example something like this:

<table>
    <tr><th>Name</th><th>Age</th><th>Country</th></tr>
    <tr><td>Geronimo</td><td>26</td><td>France</td></tr>
    <tr><td>Natalia</td><td>19</td><td>Spain</td></tr>
    <tr><td>Silvia</td><td>32</td><td>Russia</td></tr>
</table>

And you want to download it as a CSV table format.

First of all, you need to transform from HTML to CSV.

	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);

After that, you can download it using Blob and a link.

    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);

    // Launch
    downloadLink.click();

Here a real example:

2 replies
  1. japanfever
    japanfever says:

    //VFdGeWFXOGdVR0ZzYjIxdklGUnZjbkpsY204Z1BHMXdZV3h2Ylc5QWFXaHRZVzR1WTI5dFBnbz0K
    function table2csv(tableid) {
    var csv = [];
    var rows = document.querySelectorAll(‘#’ + tableid + ‘ 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(','));
    }
    return csv.join('\n');
    }

    • Genesis
      Genesis says:

      Hi japanfever, absolutely yes, thanks for your comment, my first example was from an old code where there was not DOM. In both cases it works but yours is easier and faster when you already have the HTML table in the website. I have updated this post with your snippet, thanks xD

Comments are closed.