Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create and download CSV file in JavaScript?
JavaScript provides powerful capabilities to manipulate data and handle various file formats. When developing web applications, you often need to export data as CSV files for users to download - such as order details from e-commerce platforms or transaction records from banking applications.
In this tutorial, we will learn to create CSV files from JavaScript data and automatically download them to the user's device.
Syntax
The basic approach involves converting data to CSV format and using a virtual anchor element for download:
// Convert data to CSV format
let csvData = 'Header1,Header2,Header3<br>';
data.forEach(function (row) {
csvData += row.field1 + ',' + row.field2 + ',' + row.field3 + '<br>';
});
// Create download link
let anchor = document.createElement('a');
anchor.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData);
anchor.download = 'filename.csv';
anchor.click();
Example 1: Creating CSV from Object Array
This example demonstrates creating and downloading a CSV file from an array of laptop objects:
<html>
<body>
<h3>Creating and downloading CSV file from JavaScript data</h3>
<button onclick="downloadFile()">Download CSV file</button>
<script>
let laptops = [
{brand: 'HP', processor: 'i3', price: 30000, ram: 4},
{brand: 'Dell', processor: 'i5', price: 50000, ram: 8},
{brand: 'Apple', processor: 'i7', price: 70000, ram: 16},
{brand: 'Lenovo', processor: 'i3', price: 35000, ram: 4},
{brand: 'Asus', processor: 'i5', price: 45000, ram: 8},
{brand: 'Acer', processor: 'i7', price: 65000, ram: 16}
];
function downloadFile() {
// Add CSV header
let csvData = 'Brand,Processor,Price,RAM<br>';
// Add data rows
laptops.forEach(function (row) {
csvData += row.brand + ',' + row.processor + ',' + row.price + ',' + row.ram + '<br>';
});
// Create and trigger download
let anchor = document.createElement('a');
anchor.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData);
anchor.target = '_blank';
anchor.download = 'laptops.csv';
anchor.click();
}
</script>
</body>
</html>
Example 2: Creating CSV from API Data
This example fetches JSON data from an API and converts it to a downloadable CSV file:
<html>
<body>
<h3>Creating CSV file from API data</h3>
<button onclick="downloadFile()">Download CSV file</button>
<script>
function downloadFile() {
let APIURL = "https://dummyjson.com/products";
// Fetch data from API
fetch(APIURL)
.then(response => response.json())
.then(data => {
let csvData = [];
// Get headers from first object
let headers = Object.keys(data.products[0]);
csvData.push(headers.join(','));
// Process each data row
for (let row of data.products) {
let rowValues = headers.map(header => {
// Escape quotes and wrap in quotes
let value = ('' + row[header]).replace(/"/g, '""');
return `"${value}"`;
});
csvData.push(rowValues.join(','));
}
// Download the CSV file
downloadCSV(csvData.join('<br>'));
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
function downloadCSV(csvData) {
let anchor = document.createElement('a');
anchor.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData);
anchor.target = '_blank';
anchor.download = 'products.csv';
anchor.click();
}
</script>
</body>
</html>
How It Works
The CSV generation process involves two main steps:
- Data Conversion: Transform JavaScript objects into comma-separated values with proper escaping for special characters
- File Download: Create a data URL with the CSV content and use a virtual anchor element to trigger the browser's download mechanism
Key Points
- Always include headers as the first row of your CSV file
- Use
encodeURI()to properly encode special characters - Wrap values in quotes and escape internal quotes to handle commas in data
- Set the
downloadattribute to specify the filename - The
data:text/csvMIME type tells the browser to treat it as a CSV file
Conclusion
Creating and downloading CSV files in JavaScript is straightforward using data URLs and virtual anchor elements. This technique works with both static data and dynamic API responses, making it perfect for data export features in web applications.
