最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to create a csv file with vue.js - Stack Overflow

matteradmin6PV0评论

I want to create a csv file with the plugin 'csv-writer' in a vuejs file. I took the example code of the plugin and made it works with .js file.

Now, I want to adapt the code so that it works in my vue.js file the thing is that I don't get what's the equivalent of

const createCsvWriter = require('csv-writer').createObjectCsvWriter;

here is the example :

const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({
    path: 'file.csv',
    header: [
        {id: 'name', title: 'NAME'},
        {id: 'lang', title: 'LANGUAGE'}
    ]
});
 
const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'}
];
 
csvWriter.writeRecords(records)       // returns a promise
    .then(() => {
        console.log('...Done');
    });

What I tried in my vue.js file :

<template>
    <div>
      <v-btn text @click.prevent="exportData()">
            Export CSV
        </v-btn>
   </div>
</template>


<script>

import createCsvWriter from 'csv-writer'

    export default {
        data () {
            return {
                csvWriter : createCsvWriter({
                     path: 'file.csv',
                        header: [
                            {id: 'name', title: 'NAME'},
                            {id: 'lang', title: 'LANGUAGE'}
                      ]  
                }),
                records : [
                    {name: 'Bob',  lang: 'French, English'},
                    {name: 'Mary', lang: 'English'}
                ],
            }
        },
        methods: {
            
            async exportData(){
                this.csvWriter.writeRecords(this.records);      // returns a promise
                console.log('...Done');
               
               },
        }
    }
</script>

I want to create a csv file with the plugin 'csv-writer' in a vuejs file. I took the example code of the plugin and made it works with .js file.

Now, I want to adapt the code so that it works in my vue.js file the thing is that I don't get what's the equivalent of

const createCsvWriter = require('csv-writer').createObjectCsvWriter;

here is the example :

const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({
    path: 'file.csv',
    header: [
        {id: 'name', title: 'NAME'},
        {id: 'lang', title: 'LANGUAGE'}
    ]
});
 
const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'}
];
 
csvWriter.writeRecords(records)       // returns a promise
    .then(() => {
        console.log('...Done');
    });

What I tried in my vue.js file :

<template>
    <div>
      <v-btn text @click.prevent="exportData()">
            Export CSV
        </v-btn>
   </div>
</template>


<script>

import createCsvWriter from 'csv-writer'

    export default {
        data () {
            return {
                csvWriter : createCsvWriter({
                     path: 'file.csv',
                        header: [
                            {id: 'name', title: 'NAME'},
                            {id: 'lang', title: 'LANGUAGE'}
                      ]  
                }),
                records : [
                    {name: 'Bob',  lang: 'French, English'},
                    {name: 'Mary', lang: 'English'}
                ],
            }
        },
        methods: {
            
            async exportData(){
                this.csvWriter.writeRecords(this.records);      // returns a promise
                console.log('...Done');
               
               },
        }
    }
</script>
Share Improve this question asked Jul 6, 2022 at 13:30 Barre MathisBarre Mathis 822 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

I chose a vue plugin named vue-json-to-csv to achieve it =)

csv-writer is for node.js, not client-side JavaScript.

Something like this ought to work.

    var data = [
      ['name1', 'city1', 'some other info'],
      ['name2', 'city2', 'more info']
    ];

    // Building the CSV from the Data two-dimensional array
    // Each column is separated by ";" and new line "\n" for next row
    var csvContent = '';
    data.forEach(function(infoArray, index) {
      dataString = infoArray.join(';');
      csvContent += index < data.length ? dataString + '\n' : dataString;
    });

    // The download function takes a CSV string, the filename and mimeType as parameters
    // Scroll/look down at the bottom of this snippet to see how download is called
    var download = function(content, fileName, mimeType) {
      var a = document.createElement('a');
      mimeType = mimeType || 'application/octet-stream';

      if (navigator.msSaveBlob) { // IE10
        navigator.msSaveBlob(new Blob([content], {
          type: mimeType
        }), fileName);
      } else if (URL && 'download' in a) { //html5 A[download]
        a.href = URL.createObjectURL(new Blob([content], {
          type: mimeType
        }));
        a.setAttribute('download', fileName);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else {
        location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
      }
    }

    download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8');

Post a comment

comment list (0)

  1. No comments so far