In this blog, we will see how to export an HTML table to a CSV file, using the simple tabletoCSV jQuery plugin.
First, we will create an HTML table, which shows the employee details and an Export to CSV button, as shown below.
  1. <div>
  2. <table id="mytable" cellpadding="5" border="1" cellspacing="0">
  3. <thead>
  4. <tr>
  5. <th>
  6. Employee Name
  7. </th>
  8. <th>
  9. Age
  10. </th>
  11. <th>
  12. Designation
  13. </th>
  14. <th>
  15. Experience
  16. </th>
  17. </tr>
  18. </thead>
  19. <tbody>
  20. <tr>
  21. <td>
  22. Rajeev
  23. </td>
  24. <td>
  25. 31
  26. </td>
  27. <td>
  28. Developer
  29. </td>
  30. <td>
  31. 6
  32. </td>
  33. </tr>
  34. <tr>
  35. <td>
  36. Sandhya
  37. </td>
  38. <td>
  39. 27
  40. </td>
  41. <td>
  42. Tester
  43. </td>
  44. <td>
  45. 2
  46. </td>
  47. </tr>
  48. <tr>
  49. <td>
  50. Ramesh
  51. </td>
  52. <td>
  53. 25
  54. </td>
  55. <td>
  56. Designer
  57. </td>
  58. <td>
  59. 1
  60. </td>
  61. </tr>
  62. <tr>
  63. <td>
  64. Sanjay
  65. </td>
  66. <td>
  67. 32
  68. </td>
  69. <td>
  70. Developer
  71. </td>
  72. <td>
  73. 5
  74. </td>
  75. </tr>
  76. <tr>
  77. <td>
  78. Ramya
  79. </td>
  80. <td>
  81. 23
  82. </td>
  83. <td>
  84. Developer
  85. </td>
  86. <td>
  87. 1
  88. </td>
  89. </tr>
  90. </tbody>
  91. </table>
  92. <br />
  93. <button onclick="exporttocsv()">
  94. Export to CSV</button>
  95. </div>
Running the page will look as shown below.

Now, we reference the jQuery file and tabletoCSV file in our head section.
  1. <script src="jquery.min.1.11.1.js" type="text/javascript"></script>
  2. <script src="jquery.tabletoCSV.js" type="text/javascript"></script>
Now, we write our exporttocsv() function.
  1. <script type="text/javascript">
  2. function exporttocsv() {
  3. $("#mytable").tableToCSV({
  4. filename: 'employeelist'
  5. });
  6. }
  7. </script>
In the script given above, filename is the name given to the downloading CSV file.

Hence, now we will run the page and click Export to CSV button.

Our CSV file will be downloaded. On opening the file, we can see the data of our table, as shown below.



That's it. Our HTML table to CSV exporting is complete.

Reference

jquery-table2csv - http://www.jqueryscript.net/table/jQuery-Plugin-To-Export-Table-Data-To-CSV-File-table2csv.html

Summary

In this blog, we have learned how to export an HTML table to a CSV file, using tabletoCSV jQuery plugin.
I hope this will be helpful.