JavaScript create and download CSV file

CSV files are crucial in the field of computer science, particularly in web development and database management. Situations may arise where users need to download data from a web browser. In such instances, programmers can utilize CSV files to enable users to download this data in a structured tabular format from the website. The CSV file format is commonly employed by developers for facilitating the download of website data by users.

Comma-separated values (CSV) is a straightforward and convenient format for storing website data in a tabular layout. JavaScript can be utilized to gather information from an HTML page and generate a CSV file, either programmatically or manually. By opening the CSV file in MS Excel, users can view the contained data. CSV files are commonly essential for backing up data in nearly all databases.

Programmers utilize CSV files to extract data from websites. JavaScript can generate and enable the download of CSV files. This section will explain the process of exporting HTML table data from a website into a CSV file.

How can you download the CSV file?

By utilizing JavaScript, you have the ability to extract information from an HTML document and efficiently save it in a CSV file for downloading. Employ JavaScript in conjunction with HTML to generate the data and enable users to download it in CSV form effortlessly.

In this section, you will learn how to retrieve a CSV file from both a client-side and a server-side perspective.

Why needs CSV file?

  • CSV files store and display the data in tabular form which is easy to understand.
  • It is easy and simple to use and implement. So, programmers prefer CSV to download the data of the website in .csv format.
  • It does not require any third-party libraries to create and download.
  • By using simple JavaScript methods and parameters, you can easily use the CSV file in your website.

The upcoming illustration is a straightforward example from this chapter illustrating the process of generating and downloading a CSV file.

Implementation

In order to generate data for your CSV file, you can simply construct a multi-dimensional array to store the information intended for the HTML page. It is advisable to manually create the data for educational purposes rather than extracting it directly from the HTML page.

To accomplish this task, you should generate a multidimensional array in JavaScript and input various values manually. For example, you can input data such as "Justin Bieber, 24, Singer, London" where each piece of information like Name, Age, Profession, and City corresponds to a different element within the array. This array structure will allow you to then create a CSV file.

Refer to the code snippet below for the implementation of generating and downloading a CSV file.

Create and download CSV file

Example 1

In this illustration, we are going to generate a multi-dimensional array and input data to produce a CSV file. Additionally, we will include a download button for users to download this data. Upon clicking the designated button, the data will initiate downloading in the .csv file format.

Copy Code

Example

<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 download_csv_file() {



    //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";

    });

 

    //display the created CSV data on the web browser 

    document.write(csv);



   

    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="download_csv_file()"> Download CSV </button>



</body>

</html>

Output

Attempt to run the provided code on a web platform to view the output demonstrated in the screenshot below:

To acquire the CSV data generated in this file, simply click on the provided "Download CSV" button. The downloaded CSV file will also be viewable on the web interface.

Open the downloaded CSV File

Check the file extension of the downloaded content, which should be in the format .csv. To examine the contents, open the downloaded CSV file using MS-Excel to view the information it contains. The data within the CSV file will be displayed in a structured table format. Upon opening the CSV file, we will demonstrate how the data appears both in Microsoft Excel and Notepad.

Refer to the screenshot below showing CSV data in MS-Excel. Additionally, the CSV data has been presented on a web browser for your reference.

CSV file on MS-Excel

CSV file on Notepad

Export and download the HTML table data of webpage into CSV file

Another method to retrieve website data in CSV format involves enabling users to download the data in this format. JavaScript provides a built-in function that allows programmers to export website data, typically HTML table data, into a CSV file that can be viewed in MS-Excel.

Example

In this instance, we are going to demonstrate the process of transferring the data from an HTML table on a webpage into a CSV file, which can then be downloaded. A download button will be implemented to enable users to acquire this CSV file effortlessly. Upon clicking this designated button, the data will initiate the download process in the .csv file format.

Copy Code

Example

<html>

<head>

<title> Export HTML table Data to CSV using JavaScript </title>



<style>

*{

     color:#2b2b2b;

     font-family: "Roboto Condensed";

}

table { 

     width:40%;

}

th {

     text-align:left;

     color:#4679bd;

}

</style>

</head>



<script>

//user-defined function to download CSV file

function downloadCSV(csv, filename) {

    var csvFile;

    var downloadLink;

   

    //define the file type to text/csv

    csvFile = new Blob([csv], {type: 'text/csv'});

    downloadLink = document.createElement("a");

    downloadLink.download = filename;

    downloadLink.href = window.URL.createObjectURL(csvFile);

    downloadLink.style.display = "none";



    document.body.appendChild(downloadLink);

    downloadLink.click();

}



//user-defined function to export the data to CSV file format

function exportTableToCSV(filename) {

   //declare a JavaScript variable of array type

   var csv = [];

   var rows = document.querySelectorAll("table tr");

 

   //merge the whole data in tabular form 

   for(var i=0; i<rows.length; i++) {

	var row = [], cols = rows[i].querySelectorAll("td, th");

	for( var j=0; j<cols.length; j++)

	   row.push(cols[j].innerText);

	csv.push(row.join(","));

   } 

   //call the function to download the CSV file

   downloadCSV(csv.join("\n"), filename);

}

</script>



<body>

<!-- create table and provide data inside it -->

<table>

<tr>

	<th> Name </th>

	<th> Profession </th>

	<th> Age </th>

	<th> Hobby </th>

</tr>

<tr>

	<td> Cristiano </td>

	<td> Hacker </td>

	<td> 24 </td>

	<td> Travelling, Sky-diving </td>

</tr>

<tr>

	<td> Jenifer </td>

	<td> Photographer </td>

	<td> 22 </td>

	<td> Cooking </td>

</tr>

<tr>

	<td> Simon </td>

	<td> Travelling-guide </td>

	<td> 35 </td>

	<td> Dancing, Gardening </td>

</tr>

<tr>

	<td> Cristiano Ronaldo </td>

	<td> Footballer </td>

	<td> 29 </td>

	<td> Singing </td>

</tr>

</table>

<p><b> Click the Download CSV button to download the created data </b></p>



<!-- button to call the user-defined function to download CSV file data -->

<button onclick="exportTableToCSV('person.csv')"> Export HTML table to CSV File </button> 

</body>

</html>

Output

Save the code provided above into a file and run it within a web environment. The output will be displayed as shown in the image on the web browser, displaying an HTML table with multiple rows of data.

To initiate the download of the data in CSV format, simply click on the designated button labeled "Export to HTML table to CSV File". This action will prompt the file to be saved under the name "person.csv".

To view the information stored in this file, you can access it through MS-Excel. Once you have downloaded the file, open it to examine the data, which will be displayed similarly to the content of a table in an HTML webpage.

Input Required

This code uses input(). Please provide values below: