As we know a CSV file is a Comma Separated Values file that contains plain texts as a list of data. So, we gonna create a function that will take all data from an HTML table, separate all the td (table data/cell) or th (table header) with a comma and for every tr (table row) we’ll use a line break (newline).

We’ll use BLOB to convert those raw data into a file-like object. Then we’ll create an URL for that object using URL.createObjectURL() method. Next, we’ll create an “a” tag element, we put the BLOB object’s URL in it’s href attribute and give a file name in the download attribute. Finally, we’ll insert it in the dom, trigger its click event and remove it from the dom.

 

function export_table_to_csv (table, csv_name) {
	var csv = [];
	var rows = table.querySelectorAll("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(","));		
	}

	var csv_string = csv.join("\n");
	var csv_blob = new Blob([csv_string], {type: "text/csv"});
	var csv_href = window.URL.createObjectURL(csv_blob);

	var a = document.createElement('a');
	a.href = csv_href;
	a.download = csv_name + '.csv';
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
}

// You can use the function like this - 
var table = document.getElementById('mytable');
export_table_to_csv(table, 'MyCSV');

Now we’ve got a working function that accepts an HTML table and a name for the CSV file, which will start downloading the CSV file.