In this blog, we will see how to export an HTML table to an Excel file, using the simple table2excel jQuery plugin. First we, will create the HTML table, which shows employee details and an "Export to Excel" button, as shown below.
- <div>
- <table id="mytable" cellpadding="5" border="1" cellspacing="0">
- <thead>
- <tr>
- <th>
- Employee Name
- </th>
- <th>
- Age
- </th>
- <th>
- Designation
- </th>
- <th>
- Experience
- </th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>
- Rajeev
- </td>
- <td>
- 31
- </td>
- <td>
- Developer
- </td>
- <td>
- 6
- </td>
- </tr>
- <tr>
- <td>
- Sandhya
- </td>
- <td>
- 27
- </td>
- <td>
- Tester
- </td>
- <td>
- 2
- </td>
- </tr>
- <tr>
- <td>
- Ramesh
- </td>
- <td>
- 25
- </td>
- <td>
- Designer
- </td>
- <td>
- 1
- </td>
- </tr>
- <tr>
- <td>
- Sanjay
- </td>
- <td>
- 32
- </td>
- <td>
- Developer
- </td>
- <td>
- 5
- </td>
- </tr>
- <tr>
- <td>
- Ramya
- </td>
- <td>
- 23
- </td>
- <td>
- Developer
- </td>
- <td>
- 1
- </td>
- </tr>
- </tbody>
- </table>
- <br />
- <button onclick="exportexcel()">
- Export to Excel</button>
- </div>
Running the page will look as shown below.
Now, we reference the jQuery file and table2excel file in our head section.
- <head runat="server">
- <title>Table 2 Excel</title>
- <script src="jquery.min.1.11.1.js" type="text/javascript"></script>
- <script src="jquery.table2excel.min.js" type="text/javascript"></script>
- </head>
Now, we write our exportexcel() function, as shown below.
- <script type="text/javascript">
- function exportexcel() {
- $("#mytable").table2excel({
- name: "Table2Excel",
- filename: "myFileName",
- fileext: ".xls"
- });
- }
- </script>
In the script given above, the filename is the name of the file downloaded and fileext is the extension of the file to be downloaded, which is XLS.
Now, we will run the page and click on Export to Excel button.
Our Excel file will be downloaded. On opening the file, we can see the data of our table, as shown below.
Our Excel exporting is complete.
Reference
jquery-table2excel
Summary
In this blog, we have learned how to export HTML table to an Excel file, using the table2excel jquery plugin. I hope this will be helpful.