This post will show you how to create a downloadable CSV file from an HTML table using jQuery. To make everything work, we also need a server-side script that will receive our input to turn it into a CSV file. First, we need to create a jQuery plugin to retrieve all the relevant information from an HTML table and format them accordingly. Our plugin should not assume that the target table uses a proper and semantic structure but only that table headers must be present (the th
element). So here's our plugin:
(function($) { $.fn.tableToCSV = function() { var headers = []; var csv = ''; this.find('th').each(function() { var $th = $(this); var text = $th.text(); var header = '"' + text + '"'; headers.push(header); }); csv += headers.join(',') + "\n"; this.find('tr').not('tr:first-child').each(function() { $(this).find('td').each(function() { var row = $(this).html(); if(!$(this).is('td:last-child')) { row += ','; } else { row += "\n"; } csv += row; }); }); return csv; }; })(jQuery);
This plugin uses both an array-based and a string-based approach. First, it retrieves all table headers and convert them into a string ended by a new line character. Second, it loops through all the remaining table rows to fetch the content of table cells and add it to the variable csv
. In this case, if a table cell is not the last child of its parent row, then a trailing comma is added just after it. Otherwise, our plugin simply adds a new line character. Note that in this case we've used the html()
method, because a table cell can actually contain other elements.
We can use our plugin as follows:
$(document).ready(function() { $('#convert').click(function() { var href = 'path/to/script.php?csv='; var data = $('#test').tableToCSV(); href += encodeURIComponent(data); $(this).attr('href', href); }); });
We use the global JavaScript encodeURIComponent()
function to pass our CSV data along with the URL. Finally, our PHP script is as follows:
header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename="table.csv"'); $csv = urldecode($_GET['csv']); echo $csv;
In this case, our URL is decoded using the urldecode()
function. Note also that the second header declaration is required to make our CSV file downloadable. You can see the demo below.