Let’s get started.
Export HTML Table to Excel (XLSX or XLS) File with Libraries
First, we will see how to use third-party libraries to convert HTML table data to XLSX or XLS format and download it as an excel file.
As I said there are many libraries that you can use but for now we will take references from two libraries and convert HTML to excel using them.
The TabletoExcel library is very simple and easy to use. You can export your HTML table to valid excel file effortlessly.
You just have to embed this library in your page where the HTML table shows that you want to convert it into an excel file.
Create an HTML page for example and have a sample table as follows.
Now just add the following script tag for the TabletoExcel library to your page’s footer. You can also add a CDN link.
In the above code, we used the
convert() function of the TabletoExcel library to convert the HTML data to an excel file. Then we get the table content by ID and pass the file name and sheet name parameters.
The TableExport library is also easy to implement on your web page to export the HTML table to an excel file in .xlsx or .xls format.
You can also use this library to convert HTML table to CSV, and text files.
Let’s take the same above HTML table for reference. You can create your own as your requirements or use the existing one.
Add the following script tag for the TableExport library to your page’s footer before closing the
<body> tag. You can also add a CDN link.
Note: If you want to export the HTML table to XLSX file format then you also have to add one more library script tag for xlsx core.
Here in the above code, we used the TableExport function by passing the table ID and additional parameters for filename, sheet name, default formats, etc. There are more parameters you can check here.
Export HTML Table to Excel (XLSX or XLS) File without Library
topStudents_sheet() and take the important variables like dataType, table content, etc.
You can run this function on click event to targetting to table. So simply add the button to your page and add the click event for it as follows.
You can target the specific table ID and give the dynamic filename by modifying the above function and button code by passing the table ID and filename as function parameters.
Hope it is helpful for you. Please send your opinions or suggestions in your comment sections. Also, share this tutorial with your friends.