Export HTML table to CSV file


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


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

    // 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

    // Launch

Here a real example:

2 replies
  1. japanfever
    japanfever says:

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