Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading a CSV of file using Vue and JS

I have a field called csvdata that contains an array of the following format:

[
    [1,2,3],
    [4,5,6],
    [7,8,9]
]

I'm trying to download a CSV file of this data. I'm using Vue so it looks like:

<button type="button" class="btn btn-info action_btn" v-on:click="downloadCSVData">
      Download
</button>

How should the downloadCSVData function look like?

like image 942
vesii Avatar asked Oct 08 '19 19:10

vesii


Video Answer


1 Answers

I think you can create a method like so, assuming csvdata is a data property accessible by this in your Vue component:

downloadCSVData() => {
    let csv = 'Put,Column,Titles,Here\n';
    this.csvdata.forEach((row) => {
            csv += row.join(',');
            csv += "\n";
    });
 
    const anchor = document.createElement('a');
    anchor.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    anchor.target = '_blank';
    anchor.download = 'nameYourFileHere.csv';
    anchor.click();
}
like image 96
j3py Avatar answered Sep 27 '22 20:09

j3py