
I previously posted this method for Mootools, and now here it is for jQuery.
Clients often ask to have a sorted list exportable via a link to a CSV file that they can open in Excel or whatever spreadsheet software they use. I could find two jQuery plugins for exporting table data to Excel, but I wasn’t comfortable with their reliance on producing popups (that could easily be blocked), or sending data as a querystring to a javascript function that sorts and formats the CSV. Here is a simple, plugin free way of asynchronously generating a .csv file using jQuery and PHP.
In my case I had a form with search fields that submits to a PHP search script, and returns data which is formatted into a table and displayed to the user. My method for then exporting this to Excel is to add a link on the page which when clicked, changes the action of the form to a different processing script which outputs the .csv, then resubmitting the form to this redirected URL. The hard work is done with PHP instead of Javascript.
<span id="csv-link" style="cursor: pointer"><strong>Download as a CSV file</strong></span>
1 2 3 4 5 6 7 8 | jQuery(function ($) { $("#csv-link").click(function () { $(function() { $("#searchform").attr('action','/export.php'); $('#searchform').submit(); }); }); }); |
Now as long as your PHP file is configured to return the correct headers for the file type you would like downloaded, this should trigger a download. Here’s an example of some PHP to download a .csv file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php /* Export.php: here you would call the search function that is used to query the database and return an array to generate a table, except we will loop over the results here and produce .csv lines instead */ $filename = 'download.csv'; $out = 'Heading One, Heading Two, etc'.chr(10); //$search_result = result_of_your_search_function($_POST); foreach($search_result as $row){ $out .= $row->item_one.', '.$row->item_two.', etc'.chr(10); } header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Length: " . strlen($out)); header("Content-type: text/x-csv"); header("Content-Disposition: attachment; filename=$filename"); echo $out; exit; ?> |
Your file will now automatically download.