How to create a csv file with vue.js?

by elisha_langworth , in category: Javascript , a year ago

How to create a csv file with vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 10 months ago

@elisha_langworth 

To create a CSV file with Vue.js, you can use the csv-stringify package, which provides an easy way to convert data into CSV format. Here's how you can implement it:

  1. Install the csv-stringify package using npm or yarn: npm install csv-stringify
  2. Import the csv-stringify package in your Vue component: import { stringify } from 'csv-stringify';
  3. In your component's methods or computed properties, define the data that you want to convert into CSV format. For example: data() { return { csvData: [ ['Name', 'Age', 'Email'], ['John Doe', 25, '[email protected]'], ['Jane Smith', 30, '[email protected]'], ['Dave Johnson', 35, '[email protected]'] ] }; }
  4. Create a method that converts the data into CSV format and triggers the download of the CSV file: methods: { downloadCSV() { stringify(this.csvData, (err, output) => { if (err) { console.error(err); return; } const blob = new Blob([output], { type: 'text/csv' }); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'data.csv'); document.body.appendChild(link); link.click(); document.body.removeChild(link); }); } }
  5. In your template, add a button or a link to trigger the downloadCSV method:


Now, when you click the "Download CSV" button, it will generate a CSV file and initiate the download with the filename "data.csv". The file will contain the data specified in the csvData property, formatted in CSV format.