How to Export CSV Data Using JavaScript?

Estimated read time 2 min read

To export CSV data using JavaScript, you can follow the following steps:

  1. Create a data array: First, you need to create an array of data that you want to export in CSV format. This data can be anything like a list of objects or arrays.
  2. Convert data into CSV format: Once you have data, you need to convert it into CSV format. To do this, you can create a function that takes an array of data and returns a string in CSV format. Here is an example of a CSV conversion function:
function convertToCSV(data) {
  const header = Object.keys(data[0]).join(',');
  const rows = data.map(item => Object.values(item).join(','));
  return header + '\n' + rows.join('\n');
}
  1. Create a CSV file: To create a CSV file, you can create a Blob object and set its type to ‘text/csv’. Then, you can create a URL object using the URL.createObjectURL method and set its value to the Blob object. Here is an example:
const csv = convertToCSV(data);
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
  1. Download the file: Finally, you need to create a link and set its href to the URL object that you created in the previous step. Then, you can add the link to the page and click on it programmatically to download the file. Here is an example:
const link = document.createElement('a');
link.href = url;
link.download = 'data.csv';
document.body.appendChild(link);
link.click();

Putting it all together, here is an example of how you can export CSV data using JavaScript:

const data = [
  { name: 'John Doe', age: 30, email: 'john@example.com' },
  { name: 'Jane Doe', age: 25, email: 'jane@example.com' },
  { name: 'Bob Smith', age: 40, email: 'bob@example.com' }
];

function convertToCSV(data) {
  const header = Object.keys(data[0]).join(',');
  const rows = data.map(item => Object.values(item).join(','));
  return header + '\n' + rows.join('\n');
}

const csv = convertToCSV(data);
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);

const link = document.createElement('a');
link.href = url;
link.download = 'data.csv';
document.body.appendChild(link);
link.click();

When you run this code, it will create a CSV file and download it to your computer with the name “data.csv”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply