How to create and download CSV file in JavaScript ?
Sometimes we need to fetch the data in the form of a CSV file, it might be user’s details or other data for machine learning or analytics purposes. We can easily fetch the data from any javascript object or JSON file and download it in the form of a CSV file.
In this article, we will deal with 2 data sources:
- Javascript object
- JSON object
Data Source: Javascript Object
Approach: In short, 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 () {
const data = {
id: 1,
name: "Geeks" ,
profession: "developer"
}
}
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) {
csvRows = [];
const headers = Object.keys(data);
csvRows.push(headers.join( ',' ));
const values = Object.values(data).join( ',' );
csvRows.push(values)
return csvRows.join( '\n' )
}
const get = async function () {
const data = {
id: 1,
name: "Geeks" ,
profession: "developer"
}
console.log(csvmaker(data));
}
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
const download = function (data) {
const blob = new Blob([data], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob)
const a = document.createElement( 'a' )
a.setAttribute( 'href' , url)
a.setAttribute( 'download' , 'download.csv' );
a.click()
}
const csvmaker = function (data) {
csvRows = [];
const headers = Object.keys(data);
csvRows.push(headers.join( ',' ));
const values = Object.values(data).join( ',' );
csvRows.push(values)
return csvRows.join( '\n' )
}
const get = async function () {
const data = {
id: 1,
name: "Geeks" ,
profession: "developer"
}
const csvdata = csvmaker(data);
download(csvdata);
}
const btn = document.getElementById( 'action' );
btn.addEventListener( 'click' , get);
|
Output:
Data Source: JSON Object
The process is similar for JSON objects
- We need to make a javascript object mapping through a JSON file. It will work the same as the data we used previously.
Javascript
const get = async function () {
const res = await fetch(url);
const jsonobj = await res.json();
const jsondata = jsonobj.statewise
const data = jsondata.map(row => ({
state: row.state,
statecode: row.statecode,
active: row.active,
confirmed: row.confirmed,
deaths: row.deaths
}))
const csvdata = csvmaker(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) {
csvRows = [];
const headers = Object.keys(data[0]);
csvRows.push(headers.join( ',' ));
for (const row of data) {
const values = headers.map(e => {
return row[e]
})
csvRows.push(values.join( ',' ))
}
return csvRows.join( '\n' )
}
|
Output:
Last Updated :
16 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...