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>';

In PHP, your CSV export script might look like:

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

In Python, you might use:

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


Leave a Reply

Your email address will not be published. Required fields are marked *