How To Export HTML Table In Excel Using jQuery

To export an HTML table in Excel using jQuery, you can use a plugin called “table2excel”. This plugin allows you to export HTML tables to Excel spreadsheets.

Here are the steps to use this plugin:

 

Step 1 :First, you need to include the jQuery library and the “table2excel” plugin in your HTML file. You can use the following code to do this:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/table2excel/dist/jquery.table2excel.min.js"></script>

 

Step 2: Next, you need to add a button or a link to your HTML file that will trigger the export process. You can use the following code to create a button:

<button id="export-btn">Export to Excel</button>

 

Step 3: Now, you need to add some jQuery code that will handle the click event of the button and export the HTML table to Excel. You can use the following code:

$(document).ready(function() {
  $('#export-btn').click(function() {
    $('#my-table').table2excel({
      filename: 'my-table.xlsx'
    });
  });
});

 

In this code, we first wait for the document to be ready, and then we attach a click event handler to the button with the “export-btn” id. When the button is clicked, we call the “table2excel” function on the HTML table with the “my-table” id. We also specify the filename for the Excel file as “my-table.xlsx”.

 

Step 4: Finally, you need to add an HTML table to your file that you want to export. You can use the following code as an example:

<table id="my-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>25</td>
      <td>john.doe@example.com</td>
    </tr>
    <tr>
      <td>Jane Smith</td>
      <td>30</td>
      <td>jane.smith@example.com</td>
    </tr>
  </tbody>
</table>

 

This code creates a simple HTML table with three columns: Name, Age, and Email.

When you click the “Export to Excel” button, the table will be exported to an Excel file with the name “my-table.xlsx”. You can modify the code to use your own table and filename.

 

Thanks

Submit a Comment

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

Subscribe

Select Categories