Comma Separated Values or CSV is a type of text file where each value is delimited by a comma. CSV files are very useful for the import and export of data to other software applications.
Step 1: Create an HTML table: Create a simple HTML page with a table and a button. This button will be used as a trigger to convert the table into comma-separated values and download it in the form of a CSV file. Apply your own needed CSS stylings.
When the tableToCSV() function is triggered, it accesses each table row data using the document object model. The getElementByTagName(‘tr’) retrieves all table row data and stores it in rows variable. The rows[i].querySelectorAll(‘td,th’) will get each column data of that table row. It is then stored in csvrow variable. The csvrow variable data are combined using commas to represent a row of a CSV file and then it is stored in a csv_data variable which represents the data of our CSV file in combination. We then join csv_data values using the newline character as each row in a CSV file is represented in a new line. Now our data is ready to be exported into a CSV file.
Step 3: Write a script to download the CSV file: Now that we have our converted data ready, we need to write a script to create a CSV file, feed our data into it, and trigger the browser to download it automatically after the user has clicked the download button. Since this function will be triggered after the table data is converted, we will call this function inside tableToCSV() function.
This function will take the CSV data that was formed earlier, as the argument. We will create a new file by creating a blob object of type CSV and then feed our CSV data into it. We need a link to trigger the browser window to download the file. However, we don’t have any link in our HTML to do so. So, we will create a new link using DOM and provide its attributes with the appropriate values. This link so created should not be visible to the user as this link is solely for download triggering purposes and not for any other. So we need to make sure that this link is not visible to the user and is removed once the download triggering process is over. Again we can use DOM to meet all our requirements.
Using click() event listener, we can automatically let the link be clicked and download our CSV file. Now our CSV file should be successfully downloaded.