jQuery CSV Export

Is it possible to do a CSV export with pure JavaScript? Close, but you still need the help of a server-side script to tell the browser what type of content is coming it's way.

To start, we can build on a simple jQuery plugin called table2CSV. The plugin essentially converts an HTML table to a CSV string, which you can use in your export script.

With table2CSV as a base, you could add the following jQuery snippet, which tacks an Export icon into each table caption, along with a form to post the CSV string to your processing script.

$('#content table caption').each(function() {
    d = new Date();
    filename = $(this).html().replace(/ /g, '-') + d.getMonth()
          + '-' + d.getDate() + '-' + d.getFullYear() + '.csv';
    html = '<form action="/csvExport.php" method="post">';
    html += '<input type="hidden" name="filename"
             value="' + filename + '" />';
    html += '<input type="hidden" name="csv_text"
             value="" class="csv_text" />';
    html += '<input type="image" src="/xls.png"
             alt="Export" />';
    html += '</form>';
    $(this).append(html);
    $(this).find('.csv_text').val(
            $(this).parent().table2CSV({delivery:'value'}));
});

In PHP, your CSV export script might look like:

<?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"' . $_REQUEST['filename'] . '\"");
$data=stripcslashes($_REQUEST['csv_text']);
echo $data; 
?>

In Python, you might use:

csv = context.REQUEST.get('csv_text')
filename = context.REQUEST.get('filename')
context.REQUEST.RESPONSE.setHeader('Content-type','application/msexcel')
context.REQUEST.RESPONSE.setHeader('Content-disposition','inline; filename="' + filename + '"')
return csv

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs


Tagged , .

Updated: 2011-08-08

Phil LaNasa follow us in feedly