Search code examples
javascriptcsvdatatablesexportexport-to-csv

While exporting CSV Datatable. I'm not getting multiple headers. I'm getting only 2nd row of thead in JavaScript


Hi I am using jQuery Datatables. I am trying to export CSV Datatable multiple header rows but not getting. But it is Exporting only second header row. I am using Buttons:

buttons: [{
        extend: 'CSV',
        header: true

    }, {
        extend: 'print',
        header: true
    }],

My table structure like this

<table id="example" style="color: black;" class="display compact cell-border" cellspacing="0">
    <thead>
        <tr>
            <th rowspan="2">Sl.No</th>
            <th rowspan="2">Zone</th>
            <th colspan="2">Allotted</th>
            <th colspan="2">Vacant</th>
            <th colspan="2">Amenities</th>
            <th colspan="2">Total</th>
        </tr>
        <tr>
            <th>No Of Plots</th>
            <th>Area</th>
            <th>No Of Plots</th>
            <th>Area</th>
            <th>No Of Plots</th>
            <th>Area</th>
            <th>No Of Plots</th>
            <th>Area</th>
        </tr>
    </thead>
</table>  

Solution

  • The simplest approach is to write a hard-coded CSV string, representing that first header row - so in your case:

    "","","Allotted","","Vacant","","Amenities","","Total",""\r\n
    

    Note the carriage return and linefeed at the end \r\n.

    You can use this in a JavaScript string and prepend it to the main CSV export data, using a customize function:

    $(document).ready(function() {
    
      $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [{
          extend: 'csvHtml5',
          header: true,
          customize: function ( csvData, btn, tbl ) {
            let firstHeader = '"","","Allotted","","Vacant","","Amenities","","Total",""\r\n'
            return firstHeader + csvData;
          }
        }
        }],
      } );
    
    } );
    

    Warning:

    However I have to say, having two header records in a CSV text file is generally not a good idea (in my opinion). If you want to process this CSV file automatically, having 2 header rows is going to require some extra work.

    Also, if someone wants to open the CSV file in Excel, they are not going to see the merged cells you have in the HTML table - because a CSV file is just a text file and it has no concept of merged cells, or colspans.


    Additional notes:

    Make sure you are using an up-to-date version of DataTables - one which supports csvHtml5.

    You can also get the relevant up-to-date Buttons library from the DataTables downloads page, if you don't already have it.