DataTables logo DataTables

Export to CSV/PDF without Tabletools
  • So currently, Tabletools is a great plugin for Export to CSV/PDF etc. I understand flash is used in order to locally save the exported data. Now that we are moving to a Flash-free future, has someone worked on implementing the same using Javascript (Not sure though if it is even possible with the latest JS features).

    Also, is there a plugin that anyone may have written to implement it from server-side, which may not use flash?
  • JS will likely never be possible for security/access restrictions, but you can pretty easily modify existing server-side code to output csv, then give the user a link to your script to retrieve the csv.

    You might add a new flag to the server_processing.php file that indicates output_mode

    // parse new querystring variable "o" to represent output_mode
    $output_mode = (isset($_REQUEST["o"])) ? $_REQUEST["o"] : "json"; 
    

    and check the $output_mode flag before outputting at the end of the script.

    if ($output_mode == "csv") {
      header("Content-type: text/csv");  
      header("Cache-Control: no-store, no-cache");  
      header('Content-Disposition: attachment; filename="filename.csv"');  // you can change the default file name here
    
      // send the aaData and aColumns headers
      echo csv_encode( $output["aaData"], $aColumns );   // EDIT: this was originally listed as $output->aaData which doesn't work on $output.  it's an associative array, not "object"
    }
    else {
      // default is to output json
      echo json_encode( $output );
    }
    

    and write a csv encoding routine
    function csv_encode($aaData, $aHeaders = NULL) {
      // output headers
      if ($aHeaders) echo implode(',', $aHeaders ) . "\r\n";
    
      foreach ($aaData as $aRow) {
        echo implode(',', $aRow) . "\r\n";
      }
    }


    You could add slightly more robust code to wrap data with double quotes, or escape various characters
  • Thanks fbas...... that gets me going in the right direction
This discussion has been closed.
All Discussions

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Support

Get useful and friendly help straight from the source.