Export jQuery DataTables to CSV

0
212

jQuery DataTables is a powerful and flexible JavaScript library that enhances the functionality of HTML tables. It provides features for sorting, searching, pagination, and more, making it easier to work with and display large sets of data on web pages.

To use jQuery DataTables, we need to include the jQuery library and the DataTables plugin in your HTML file. Then, we can initialize a DataTable on an existing HTML table, providing options and configurations as needed.

We can use the jQuery DataTables plugin along with JavaScript to export data to CSV format. Below is an example code that demonstrates how to achieve this. Make sure you include the jQuery library and the DataTables plugin in your HTML file.

Follow this video for complete guidance :

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Export DataTable to CSV</title>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
</head>
<body>

<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>[email protected]</td>
      <td>555-1234</td>
    </tr>
    <tr>
      <td>Jane Doe</td>
      <td>[email protected]</td>
      <td>555-5678</td>
    </tr>
    <!-- Add more rows as needed -->
  </tbody>
</table>

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

<script>
  $(document).ready(function() {
    var table = $('#example').DataTable({
      dom: 'Bfrtip',
      buttons: [
        'csv'
      ]
    });
  });
</script>

</body>
</html>

 

Comments are closed.