Let’s get started!
Export HTML Table to CSV
To export the HTML table to a CSV file, we will follow the below points.
- Create a well structured HTML table with using proper <table> tags like: <tr>, <th>, <td>. Make sure your all table tags are closed.
- Will make export function to convert HTML to CSV
- Will make download function to download the CSV file
- Click event call when click on download button
So, let’s start with the first step to creating an HTML table.
Step 1: Create HTML Table with Well Structured
We will use the <table%gt; tag to create an HTML table and show the data in it as you want. To style the data in the table with rows and columns, we will use <tr>, <th>, and <td> tags.
The above function will make new array data set with respective columns and rows. First, we make row data separated by a comma then pass the data variable in the
downloadCSVFile() function with each row start with a new line.
document.createElement() to create an anchor (<a>) element then we will assign the attribute (href in our case) value using
window.URL.createObjectURL(). But this would be hidden element in the body tag.
And finally, hit that element by
click() function. See the code below.
Step 4: Call Click Event on Download Button
This is just a simple event trigger call when some click on the download button then execute the above both functions and download the file for you.
In the above code, we target the download button with ID and trigger the
click() event when clicking on the download button. It will get the table content and pass it into the
htmlToCSV() function to convert the table rows into CSV format.
Frequently Asked Questions
What is CSV File?
A CSV (comma-separated value) file is a text file that uses a comma delimiter to separate each value. It makes one line record set, which means each line of the file is a row of table data. In the CSV file, each line will have the same number of fields, and you can say it tabular data.
What is Blob?
Blob is a data type which has file like immutable object. It can read and store text and binary data then it will represent you in a human-readable format.
Can I create any element with createElement() function?
Yes, you can create any element with createElement() function. It create the element in HTML document with specified the HTML tag name. It will also create an element if tag name not recognized by HTML.
So, That's it!