Javascript

Export html table to csv file using vanilla javascript

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.

S M Zahed Kamal

Recent Posts

PHP to remove unnecessary key and value pairs from any multi-dimensional array

Today I will share a snippet I've used in a project. Using that function, you…

2 years ago

Use vanilla JavaScript to make Ajax request

JavaScript AJAX (Asynchronous JavaScript and XML) is a technique that gives the ability to send…

3 years ago

Add animation to bootstrap carousel elements

By default, Bootstrap carousel has no way to add animations to carousel elements. Here I'm…

3 years ago

Create custom pagination template in Laravel

Laravel comes up with a paginator that generates HTML compatible with the Tailwind CSS framework.…

3 years ago

Add Bootstrap Icons in SASS or SCSS

Bootstrap introduced their icons collection in November 2019 as Bootstrap Icons (v1.0.0-alpha). At that time,…

3 years ago

Create autocomplete using vanilla JavaScript

To create autocomplete feature for input field(s), HTML's datalist tag can be the easiest solution.…

3 years ago