How to Export the jQuery Datatable data to PDF,Excel,CSV and Copy

In This Post I will show you Exporting functionality with Datatable, PHP, and MySQL.I got a huge response from readers on datatable with PHP tutorials, One of my reader request tutorial about datatable with export features. I have research and found that there is two option to add export features into datatable.

Also Checkout other tutorial of Datatable,

  • Tabletools Plugin : This plugin is used to export table data into pdf,xls,csv etc. using swf object but right its out dated.
  • ExportButton Plugin : This plugin used to export table data into pdf,xls,csv etc. using HTML5.

datatable-with-export-data

So i have taken option 2, I am integrating Export Button on Datatable with PHP.

I got one more issue with the export Button datatable plugin, You can not get full export data into pdf, excel etc. using ajax request, You can get only visible records into exported pdf,excel etc file.

I have used NON ajax manner to export datatable data with PHP.

Video Tutorial:

If you are more comfortable in watching a video that explains about Export the jQuery Datatable data to PDF,Excel,CSV and Copy, then you should watch this video tutorial.

Export DataTable Data Using Button Plugin and PHP

In this post, I will demonstrate, how to add Export functionality in datatable using Export Button Plugin. You can export data in CSV, PDF, Excel, etc format as well as Copy the table data into clipboard. Please keep in mind these functionality will work only HTML5 supported browsers.

We will cover following functionality in this Datatable Tutorial

  • Load one time data into table
  • Export and Save Datatable data into CSV
  • Export and Save Datatable data into PDF
  • Export and Save Datatable data into Excel
  • You can Copy datatable data into clipboard
  • You can Print the datatable data

Adding Necessary jQuery Datatable library and Plugins

We will include all necessary plugin and library files to export data from datatable.

https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
 
<script type="text/javascript" src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.js"></script>

We have used Datatable download builder tools generated js and css files.

Initialization Of dataTable on HTML Table

We can initialize export Button by simply adding ‘B’ into DOM element.

$( document ).ready(function() {
$('#employee_grid').DataTable({
         "processing": true,
         "sAjaxSource":"response.php",
         "dom": 'lBfrtip',
        
        });
});

Adding and customizing Export Button

We can add and customize Export Button using button json object.

"buttons": [
            {
                extend: 'collection',
                text: 'Export',
                buttons: [
                    'copy',
                    'excel',
                    'csv',
                    'pdf',
                    'print'
                ]
            }
        ]

Here, We have passed copy, excel, csv, pdf and print options into 'button' JavaScript array. This will contains all options button which you want show under Export Button. I have changed default button text to “Export” using “text” option.

The server code is same is my previous Datatable with PHP,mysql and Ajax article.

You can download source code and Demo from below link.

18 thoughts on “How to Export the jQuery Datatable data to PDF,Excel,CSV and Copy

  1. Salam,
    hey parvez i tried your code but facing some error. I am not a coder so trying to modify demos and use for my purpose. when I export it to any format it exports only the result which is visible on current page not from the next. and when i tried to download excel format, it shows it is corrupted.
    Script of index.php

    $(document).ready(function() {
    var dataTable = $(‘#employee-grid’).DataTable( {
    “processing”: true,
    “serverSide”: true,
    “ajax”:{
    url :”employee-grid-data.php”, // json datasource
    type: “post”, // method , by default get
    error: function(){ // error handling
    $(“.employee-grid-error”).html(“”);
    $(“#employee-grid”).append(‘No data found in the server’);
    $(“#employee-grid_processing”).css(“display”,”none”);
    }
    },

    “dom”: ‘lBfrtip’,
    “buttons”: [
    {
    extend: ‘collection’,
    text: ‘Export’,
    buttons: [
    ‘copy’,
    ‘excel’,
    ‘csv’,
    ‘pdf’,
    ‘print’
    ]
    }
    ],
    responsive: {
    details: {
    renderer: function ( api, rowIdx ) {
    var data = api.cells( rowIdx, ‘:hidden’ ).eq(0).map( function ( cell ) {
    var header = $( api.column( cell.column ).header() );
    return ”+header.text()+’ : ‘+api.cell( cell ).data()+”;
    } ).toArray().join(”);
    return data ? $(”).append( data ) : false;
    }
    }
    }
    });

    $(“#employee-grid_filter”).css(“display”,”none”); // hiding global search box
    $(‘.search-input-text’).on( ‘keyup click’, function () { // for text boxes
    var i =$(this).attr(‘data-column’); // getting column index
    var v =$(this).val(); // getting search input value
    dataTable.columns(i).search(v).draw();
    } );
    $(‘.search-input-select’).on( ‘change’, function () { // for select box
    var i =$(this).attr(‘data-column’);
    var v =$(this).val();
    dataTable.columns(i).search(v).draw();
    } );
    } );
    part of script of response.php:

    $query=mysqli_query($conn, $sql) or die(“employee-grid-data.php: get employees”);

    $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.

    $sql.=” ORDER BY “. $columns[$requestData[‘order’][0][‘column’]].” “.$requestData[‘order’][0][‘dir’].” LIMIT “.$requestData[‘start’].” ,”.$requestData[‘length’].” “; // adding length

    $query=mysqli_query($conn, $sql) or die(“employee-grid-data.php: get employees”);

    $data = array();

    while( $row=mysqli_fetch_array($query) ) { // preparing an array

    $nestedData=array();

    $nestedData[] = $row[“id”];

    $nestedData[] = $row[“CR_Number”];

    $nestedData[] = $row[“Gender”];

    $nestedData[] = $row[“Age”];

    $nestedData[] = $row[“Disease”];

    $nestedData[] = $row[“Affected_Region”];

    $nestedData[] = $row[“Abnormalities”];

    $nestedData[] = “ View “;

    $nestedData[] = “ Download “;

    $data[] = $nestedData;

    }

    $json_data = array(

    “draw” => intval( $requestData[‘draw’] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.

    “recordsTotal” => intval( $totalData ), // total number of records

    “recordsFiltered” => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData

    “data” => $data // total data array

    );

    echo json_encode($json_data); // send data as json format

  2. I want to add the from and to “Date” and search the data according from date and to date but i am unable to post the variable in data.php file.is this possible to post the variable in data.php file

  3. Hi,
    Is there any option to export the datatable to email client like outlook.
    Ex: Onclick of Email button, the content of jQuery DataTable should copied to outlook and from there user should send mail to whomever they want, my application is not in php.
    Any help will be really appreciated.
    Regards
    Anand

  4. Hi good day! i have a question. is it possible to print or convert only 1 data from the table or database? like for example i will print or convert only one person/data. can u give me some source code? it is really helpful for me as a student. THANKYOU VERY MUCH !!!

  5. Your Source working perfectly for all options except pdf, it shows as
    Uncaught TypeError: Cannot read properties of undefined (reading ‘Roboto-Regular.ttf’)
    Do we need to add any other option ?

Leave a Reply

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