DEV Community

Cover image for Creating and Downloading a CSV File Using Pure JavaScript - A Step by Step Guide
Hamza Ali
Hamza Ali

Posted on

Creating and Downloading a CSV File Using Pure JavaScript - A Step by Step Guide

CSV files are an essential part of computer programming. There might some cases when there is some data and you want the user to be able to download it. In that case, CSV file helps the programmer to use them to download data from the browser.

Cav files are simple to store data in the form of tables. It also doesn’t need any extra library to make the download possible. You can use plain JavaScript to implement this functionality in your App. You can open the CSV file in MS Excel and see the data present inside it. Almost every database requires CSV files to back up the data. so without any further ado let's get into it.

If you prefer to see the code in action, check out this video tutorial.

why do we need CSV files?

CSV files store data in a table format that is easy to understand.

They are simple and easy to use for programmers.

Many programmers prefer to use CSV files to download data from a website.

CSV files do not require any third-party libraries to create and download.

You can easily use a CSV file on your website using simple JavaScript methods and commands.

How to Download CSV file?

To download data in the form of a CSV file your data should be represented in a multi-dimensional array like the below code.

var csvFileData = [  
   ['Alan Walker', 'Singer'],  
   ['Cristiano Ronaldo', 'Footballer'],  
   ['Saina Nehwal', 'Badminton Player'],  
   ['Arijit Singh', 'Singer'],  
   ['Terence Lewis', 'Dancer']  
]; 
Enter fullscreen mode Exit fullscreen mode

Implementation

For this example, I am going to create my data instead of getting the actual data from the web page. For learning purposes, you can follow this blog as it is but if you are here to implement this feature with real data then you only need to replace the csvFileData with your actual data.

<html>  
<head>  
<title> Download CSV file </title>  
</head>  

<script>  
//create CSV file data in an array  
var csvFileData = [  
   ['Alan Walker', 'Singer'],  
   ['Cristiano Ronaldo', 'Footballer'],  
   ['Saina Nehwal', 'Badminton Player'],  
   ['Arijit Singh', 'Singer'],  
   ['Terence Lewis', 'Dancer']  
];  

//create a user-defined function to download CSV file   
function csvDownload() {  

    //define the heading for each row of the data  
    var csv = 'Name,Profession\\n';  

    //merge the data with CSV  
    csvFileData.forEach(function(row) {  
            csv += row.join(',');  
            csv += "\\n";  
    });  

    var hiddenElement = document.createElement('a');  
    hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);  
    hiddenElement.target = '_blank';  

    //provide the name for the CSV file to be downloaded  
    hiddenElement.download = 'Famous Personalities.csv';  
    hiddenElement.click();  
}  
</script>  

<body>  
<h3> Click the button to download the CSV file </h3>  

<!-- create an HTML button to download the CSV file on click -->  
<button onclick="cavDownload()"> Download CSV </button>  

</body>  
</html>
Enter fullscreen mode Exit fullscreen mode

Explanation

This code creates a webpage with a button labeled "Download CSV". When the button is clicked, a CSV file is created and downloaded to the user's device. The file contains a table of data with two columns, "Name" and "Profession," and five rows of data for various famous personalities.

The code first declares an array, "csvFileData," which holds the data for the table in nested arrays. Each inner array represents a row in the table, with the first element being the name and the second element being the profession.

The button's "onclick" attribute calls the function "csvDownload" when clicked. This function creates a string variable "csv" with the first row of the table as the header "Name, Profession". Then it iterates over the data in csvFileData, concatenating each row of data to the "csv" variable, separated by commas and newline characters.

The function then creates a hidden HTML "a" element, which is used to create a link for the CSV file. The link's "href" attribute is set to the "csv" variable, with the "data:text/csv;charset=utf-8," prefix and encoded using the "encodeURI" function. The "target" attribute is set to "_blank" so that the CSV file will open in a new tab/window when clicked. The "download" attribute is set to "Famous Personalities.csv" so that the downloaded file will have this name. Finally, the function triggers the click event on the hidden element, triggering the download of the file.

Conclusion

In this blog post, we have discussed the importance of CSV files in computer programming, and how they can be used to download data from a website. We have also discussed how to create and download a CSV file using plain JavaScript without the need for any third-party libraries. We walked through a code example that demonstrates how to create a webpage with a button that, when clicked, creates and downloads a CSV file with a table of data for famous personalities. It also shows how easy it is to create a CSV file using JavaScript and how it can be used to store data in a table format. This makes it easy for programmers to use and understand and is also very useful in many applications.

Top comments (0)