如何使用vue.js创建csv文件



我想在vuejs文件中创建一个带有插件'csv-writer'的csv文件。我把这个插件的示例代码,它使用js文件。

现在,我想调整一下代码让它能在vue。js文件中工作问题是,我没有得到与

等价的东西
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

示例如下:

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');
});

我在vue.js文件中尝试了什么:

<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>

我选择了一个名为vue-json-to-csv的vue插件来实现它=)

csv-writer适用于node.js,而不是客户端JavaScript。

这样的东西应该可以工作。

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');

相关内容

  • 没有找到相关文章

最新更新