How To Export HTML Table To Excel, PDF, CSV Using jQuery DataTable

HTML table to Excel, PDF, or CSV using jQuery DataTables, you can use the following steps,

Step 1. Include the necessary libraries

You need to include the following libraries in your HTML file:

  • jQuery
  • jQuery DataTables
  • Buttons extension for jQuery DataTables
  • JSZip library (for exporting to Excel)

You can include these libraries by adding the following code to your HTML file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>

Step 2. Create the HTML table

Create the HTML table that you want to export. Give it an ID so that you can reference it later:

<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>City</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Ram</td>
      <td>25</td>
      <td>Jaipur</td>
    </tr>
    <tr>
      <td>Shyam</td>
      <td>30</td>
      <td>Sikar</td>
    </tr>
    <tr>
      <td>Hanuman</td>
      <td>40</td>
      <td>Tonk</td>
    </tr>
  </tbody>
</table>

Step 3. Initialize the DataTable

Initialize the DataTable on your table, and include the necessary buttons for exporting:

$(document).ready(function() {
  $('#myTable').DataTable( {
    dom: 'Bfrtip',
    buttons: [
        'excelHtml5',
        'pdfHtml5',
        'csvHtml5'
    ]
  } );
} );

Step 4. Export the table

Now you can export the table to Excel, PDF, or CSV by clicking the corresponding button.

Note: To export to Excel, you may need to add a MIME type to your server. You can do this by adding the following line to your .htaccess file:

AddType application/vnd.ms-excel .xlsx

Alternatively, you can use the "customize" option for the Excel button to specify a different file format (e.g., CSV):

buttons: [
  {
    extend: 'excelHtml5',
    customize: function(xlsx) {
      var sheet = xlsx.xl.worksheets['sheet1.xml'];
      $('row c[r^="C"]', sheet).attr('s', '2');
    }
  },
  'pdfHtml5',
  'csvHtml5'
]

Following these steps, you can export table data in Excel and PDF formats using jQuery.

Thanks.