@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:
- Install the csv-stringify package using npm or yarn:
npm install csv-stringify
- Import the csv-stringify package in your Vue component:
import { stringify } from 'csv-stringify';
- 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]']
]
};
}
- 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);
});
}
}
- 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.