In web development, exporting data from a Vue.js application to CSV format is a common requirement, especially when dealing with tabular or structured data. In this detailed guide, we’ll explore the process of converting JSON data to a downloadable CSV file using Vue.js. By the end of this tutorial, you’ll have a clear understanding of how to implement this functionality in your Vue.js projects.
Setting Up the Vue Project:
Begin by creating a new Vue project using the Vue CLI. If you haven’t installed it, run:
npm install -g @vue/cli
vue create vue-json-to-csv
cd vue-json-to-csv
Installing Dependencies:
Install the jsonexport
library, which simplifies the conversion of JSON data to CSV:
npm install jsonexport
Designing the ExportButton Component:
- Create a
ExportButton.vue
component:
<template>
<div>
<button @click="exportToCSV">Export to CSV</button>
</div>
</template>
<script>
import jsonexport from 'jsonexport';
export default {
props: {
jsonData: {
type: Array,
required: true,
},
fileName: {
type: String,
default: 'exported_data',
},
},
methods: {
exportToCSV() {
const csvData = [];
// Convert JSON data to CSV format
jsonexport(this.jsonData, (err, csv) => {
if (err) return console.error(err);
csvData.push(csv);
// Create a Blob containing the CSV data
const blob = new Blob(csvData, { type: 'text/csv;charset=utf-8;' });
// Create a link to trigger the download
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', `${this.fileName}.csv`);
document.body.appendChild(link);
// Trigger the download
link.click();
// Clean up
document.body.removeChild(link);
URL.revokeObjectURL(url);
});
},
},
};
</script>
<style scoped>
button {
background-color: #3498db;
color: #fff;
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
Using the ExportButton Component in App.vue:
- Update the
App.vue
component:
<template>
<div id="app">
<ExportButton :jsonData="data" :fileName="fileName" />
</div>
</template>
<script>
import ExportButton from './components/ExportButton.vue';
export default {
components: {
ExportButton,
},
data() {
return {
data: [
{ Name: 'John Doe', Age: 30, City: 'New York' },
{ Name: 'Jane Smith', Age: 25, City: 'San Francisco' },
// Add more data as needed
],
fileName: 'user_data',
};
},
};
</script>
<style>
#app {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #ecf0f1;
margin: 0;
}
</style>
Explanation of the ExportButton Component:
- The
ExportButton.vue
component is a simple button that, when clicked, triggers the conversion of JSON data to CSV and initiates the download. - It utilizes the
jsonexport
library to handle the conversion process. - The CSV data is then converted into a Blob, and a download link is created dynamically.
Running the Application:
Run the following commands to see the export button in action:
npm install
npm run serve
Visit http://localhost:8080
in your browser, and you’ll find a button labeled “Export to CSV.” Clicking on it will download a CSV file containing the provided JSON data.
You can impement VueJS component to export Json Data into CSV file and download the resulting file
Follow these to implement it
VueJS component to export Json Data into CSV file and download the resulting file.
Getting started
Get the package:
yarn add vue-json-csv
Register JsonCSV in your app entrypoint:
import Vue from 'vue' import JsonCSV from 'vue-json-csv' Vue.component('downloadCsv', JsonCSV)
In your template
<download-csv :data = "json_data"> Download Data <img src="download_icon.png"> </download-csv>
Props List
Name | Type | Description |
---|---|---|
data | Array | (required) Data to be exported |
fields | Array/Function(value, key) | fields inside the Json Object that you want to export. If no given, all the properties in the Json are exported. Use the function to filter the data and only keep the properties you want. |
labels | Object/Function(value, key) | Set the label for the header row. |
name | string | filename to export, default: data.csv |
delimiter | string | Default “,”. Can be changed to anything. |
separator-excel | boolean | If true, will prepend SEP={delimiter} to the file to make it easily usable with Excel |
encoding | string | Set the wanted encoding, default to ‘utf-8’ |
advancedOptions | Object | You can set all the options of PapaParse yourself |
Example
import Vue from 'vue' import JsonCSV from 'vue-json-csv' Vue.component('downloadCsv', JsonCSV) const app = new Vue({ el: '#app', data: { json_data: [ { 'name': 'Tony Peña', 'city': 'New York', 'country': 'United States', 'birthdate': '1978-03-15', 'phone': { 'mobile': '1-541-754-3010', 'landline': '(541) 754-3010' } }, { 'name': 'Thessaloniki', 'city': 'Athens', 'country': 'Greece', 'birthdate': '1987-11-23', 'phone': { 'mobile': '+1 855 275 5071', 'landline': '(2741) 2621-244' } } ] } })
In your Template call it like
<download-csv class = "btn btn-default" :data = "json_data" name = "filename.csv"> Download CSV (This is a slot) </download-csv>
REQUIRED
- json_data: Contains the data you want to export