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: "Beginner",
profession: "developer"
}
this should be converted to:
id, name, profession
1, Beginner, developer
Step 1: Setting up the project
<!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>
const get = async function () {
// JavaScript bject
const data = {
id: 1,
name: "Beginner",
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.
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: "Beginner",
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.
// 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: "Beginner",
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: 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.
// 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
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: