How to create and download CSV file in JavaScript ?
Last Updated :
16 Sep, 2024
CSV (Comma-Separated Values) files are widely used for data transfer, analytics, and storage purposes. They allow you to easily fetch data from JavaScript or JSON objects and save it in a readable format for users, machine learning, or analytics tasks. In this article, we’ll explore how to convert data from JavaScript objects and JSON objects into CSV files and download them using JavaScript.
Why Convert Data to CSV?
- Data Analysis: CSV files are easy to import into data analysis tools like Excel, Google Sheets, or Python for further processing.
- Machine Learning: CSV is a common format for training data used in machine learning models.
- Data Export: Allow users to download data in a simple, accessible format.
Data Sources Covered
- JavaScript Object
- JSON Object
Let’s look at how to handle each of these data sources.
Data Source 1: JavaScript Object
We need the header which is referred to by javascript object keys, and rows referred by javascript object values. we need them separated by a comma in order to make it a CSV. We use Blob for building a CSV file.
// Javascript Object
const data = {
id: 1,
name: "Geeks",
profession: "developer"
}
this should be converted to:
id, name, profession
1, Geeks, developer
Step 1: Setting up the project
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<button id="action">Download csv</button>
<script type="text/javascript"
src="main.js"></script>
</body>
</html>
main.js
const get = async function () {
// JavaScript bject
const data = {
id: 1,
name: "Geeks",
profession: "developer"
}
}
// Getting element by id and adding eventlistener
// to listen everytime button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);
Step 2: Creating a csvmaker function in main.js. This function is responsible for making normal java objects in a form of CSV.
main.js
const csvmaker = function (data) {
// Empty array for storing the values
csvRows = [];
// Headers is basically a keys of an object
// which is id, name, and profession
const headers = Object.keys(data);
// As for making csv format, headers must
// be separated by comma and pushing it
// into array
csvRows.push(headers.join(','));
// Pushing Object values into array
// with comma separation
const values = Object.values(data).join(',');
csvRows.push(values)
// Returning the array joining with new line
return csvRows.join('\n')
}
const get = async function () {
// JavaScript object
const data = {
id: 1,
name: "Geeks",
profession: "developer"
}
console.log(csvmaker(data));
}
// Getting element by id and adding
// eventlistener to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);
Output:

Step 3: Creating a download function. This function will enable us to download a CSV file containing our passed data.
JavaScript
// Function to download the CSV file
const download = (data) => {
// Create a Blob with the CSV data and type
const blob = new Blob([data], { type: 'text/csv' });
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create an anchor tag for downloading
const a = document.createElement('a');
// Set the URL and download attribute of the anchor tag
a.href = url;
a.download = 'download.csv';
// Trigger the download by clicking the anchor tag
a.click();
}
// Function to create a CSV string from an object
const csvmaker = (data) => {
// Get the keys (headers) of the object
const headers = Object.keys(data);
// Get the values of the object
const values = Object.values(data);
// Join the headers and values with commas and newlines to create the CSV string
return [headers.join(','), values.join(',')].join('\n');
}
// Asynchronous function to fetch data and download the CSV file
const get = async () => {
// Example data object
const data = {
id: 1,
name: "Geeks",
profession: "developer"
};
// Create the CSV string from the data
const csvdata = csvmaker(data);
// Download the CSV file
download(csvdata);
}
// Add a click event listener to the button with ID 'action'
document.getElementById('action').addEventListener('click', get);
Output:

Data Source 2: JSON Object
The process is similar for JSON objects
- The process for JSON objects is similar to JavaScript objects. You need to map the JSON object to a JavaScript object structure and then apply the same CSV conversion and download logic.
JavaScript
// Asynchronous function to fetch and process COVID-19 data
const get = async () => {
// URL for fetching COVID-19 data
const url = 'https://data.covid19india.org/data.json';
// Fetch data from the URL and await the response
const res = await fetch(url);
// Extract the 'statewise' array from the JSON response
const { statewise } = await res.json();
// Map through the 'statewise' data and create an array of objects
const data = statewise.map(({ state, statecode, active, confirmed, deaths }) => ({
state,
statecode,
active,
confirmed,
deaths
}));
// Generate CSV data from the processed data
const csvdata = csvmaker(data);
// Download the generated CSV data
download(csvdata);
}
- We need to loop over the object values and push them to the array in the csvmaker function in main.js
JavaScript
const csvmaker = function (data) {
// Empty array for storing the values
csvRows = [];
// Headers is basically a keys of an object which
// is id, name, and profession
const headers = Object.keys(data[0]);
// As for making csv format, headers must be
// separated by comma and pushing it into array
csvRows.push(headers.join(','));
// Pushing Object values into the array with
// comma separation
// Looping through the data values and make
// sure to align values with respect to headers
for (const row of data) {
const values = headers.map(e => {
return row[e]
})
csvRows.push(values.join(','))
}
// const values = Object.values(data).join(',');
// csvRows.push(values)
// returning the array joining with new line
return csvRows.join('\n')
}
Output:

By using these simple JavaScript functions, you can easily convert JavaScript objects and JSON data into CSV format and download them. This technique is especially useful for exporting data, handling analytics, and integrating data processing workflows in web applications.
Similar Reads
Create A Download Button with Timer in HTML CSS and JavaScript
In this article, we will discuss how to create a Download button with a timer attached to it using HTML, CSS, and Javascript. Our goal is to create a button that has a timer attached to it. The download should only start after the timer has run out, which we will achieve using the setTimeout and set
2 min read
How to Convert Base64 to File in JavaScript?
In web development, Base64 encoding is often used to represent binary data, such as images or files, with a string of ASCII characters, sometimes you may be required to change this Base64 string back into a file for instance for file uploads, downloads, or processing in the browser, this article aim
2 min read
How to Create a Link in JavaScript ?
In JavaScript, a link typically refers to creating HTML hyperlinks (<a> tags) dynamically using JavaScript. You can link using a document.createElement('a'), setting attributes like href and textContent, and then appending it to the document with appendChild(). Here are some common approaches
4 min read
How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and unive
3 min read
How to Download PDF File on Button Click using JavaScript ?
Sometimes, a web page may contain PDF files that can be downloaded by the users for further use. Allowing users to download the PDF files can be accomplished using JavaScript. The below methods can be used to accomplish this task. Table of Content Using html2pdf.js libraryUsing pdfmake LibraryUsing
5 min read
How to Download Image on Button Click in JavaScript?
Downloading an image on a button click in JavaScript involves creating a mechanism to trigger the download action when a user clicks a button. Below are the approaches to download image on button click in JavaScript: Table of Content Using Anchor Tag with Download AttributeUsing Fetch APIUsing Ancho
3 min read
How to Create XML in JavaScript ?
In JavaScript, XML documents can be created using various approaches. You can define elements, attributes, and content to structure the XML data, and then serialize it into a string for use or storage. There are several approaches to creating XML in JavaScript which are as follows: Table of Content
2 min read
How To Save Text As a File in HTML CSS and JavaScript?
In this tutorial, we will learn how to save user input as a text file using HTML, CSS, and JavaScript. This can be particularly useful for web applications where users need to download their input or notes as a file. Project PreviewWe will build a simple web page that allows users to enter text in a
2 min read
How to download File Using JavaScript/jQuery ?
The ability to download files directly from a website is an essential feature for many web applications. Whether you're providing documents, images, or other data, enabling users to download files seamlessly enhances their experience and ensures they can access the content offline. This article prov
2 min read
How to Create a Download Link in HTML ?
A download link allows users to download a specific file when they click on it. The download attribute in HTML is used to create a download link. Using the anchor tag we can create a download link in the HTML. Using the <a> Anchor TagTo create a download link in HTML, use the <a> tag wit
1 min read