jQuery: Multiple methods of converting table data to CSV data

The HTML table is the preferred DOM element for displaying data in tabular format because it provides a simple yet attractive look and feel that catches user attention. HTML tables are handy tools that respond easily to various events, such as row click. Sometimes, as part of a project the end user may want to download the data presented in the table for later reference. In this post, we’ll look at how to convert HTML table data into CSV format, allowing the user to easily download the content.
There are jQuery plugins available which can do the job but first we will look at how to do it with jQuery code. A simple rule of thumb is that if something can be achieved with jQuery code, then you should always employ that method rather than using a jQuery plugin.

HTML

Within the table elements there is a hyperlink to “Download CSV” which will convert the HTML table data to CSV and then prompt you to save the CSV file as well:
<a href="" download="Data.csv" id="btnDownload">Download CSV</a>
Here the ‘download’ attribute specifies that the target will be downloaded when you click on the hyperlink. This attribute is only used if the href attribute is set. The value of the attribute will be the name of the downloaded file.

jQuery Code

The jQuery code will have a click event attached to the btnDownload hyperlink defined in HTML. Within the click event:
  • Define global array variable: arrCSVData. This variable will be used to store data after each HTML table row iteration
  • Loop through all the rows of the table element
  • This process will also check for header row. Column names in header rows are then pushed into the arrCSVData variable
  • Next, loop through all td elements inside header rows and push them into an array arrData.
  • Once inside looping is finished, use the Array.join() method to form a comma separated string  
  • After the table row loop is complete, arrCSVData variable holds all the table data. Now, again using the Array.join() method, we will convert it into a string (this time using new line character).
  • Now we have a valid CSV formatted string in csvData variable.
  • Finally, create the URL that will be set to the href attribute. Set the data to application/csv so that the browser comes to know what is going to be downloaded. Encode the final CSV data before appending it in the URL using encodeURIComponent.
Here is the complete jQuery code:
$(document).ready(function() {
   $('#btnDownload').click(function(e)
   {
     var arrCSVData = [];
     var sVal = '';
     $("#tblData").find("tr").each(function () 
     {
       if ($(this).find("th").length) 
       {
         var arrData = [];
         $(this).find("th").each(function () {
           sVal = $(this).text().replace(/"/g, '""');
           arrData.push('"' + sVal + '"');
         });
       arrCSVData.push(arrData.join(','));
      }
      else 
      {
        var arrData = [];
        $(this).find("td").each(function () {
         sVal = $(this).text().replace(/"/g, '""');
         arrData.push('"' + sVal + '"');
       });
       arrCSVData.push(arrData.join(','));
      }
   });
      var csvData = arrCSVData.join('n');
var downloadURL= 'data:application/csv;charset=UTF-8,' +  
encodeURIComponent(csvData);
      $(this).attr("href", downloadURL);
   });
});
Simple and easy.  If you don’t wish to include a header row, then remove the following portion from the above jQuery code:
if ($(this).find("th").length) 
{
var arrData = [];
      $(this).find("th").each(function () {
      sVal = $(this).text().replace(/"/g, '""');
           arrData.push('"' + sVal + '"');
});
arrCSVData.push(arrData.join(','));
}
If you would prefer not to work in the code, there are also a couple of jQuery plugins available which can do the job. These plugins also provide more flexibility and control over the CSV generation and downloading, which can be beneficial:
  1. tabletoCSV
  2. TableCSVExport
  3. table2CSV 
These jQuery plugins are easy to use. Visit their website for more information including how to use and integrate them in jQuery.

Conclusion

To sum it up, the functionality to convert table data to CSV can be achieved with simple jQuery code. However, if you want some more flexibility and don’t wish to write your own implementation, then the jQuery plugins listed above can also be employed. 


Responsive Menu
Add more content here...