分享一段将json数组数据以csv格式导出的代码:
html:
<button class="btn btn-danger" @click='exportdata'>导出</button>
js:
// 导出数据
exportdata: function() {
let tableheader = [{
colname: 'type',
coltext: '类型',
}, {
colname: 'name',
coltext: '商品名称',
}, {
colname: 'number',
coltext: '数量',
}, {
colname: 'price',
coltext: '单价',
}];
let tablebody = [{
type: '食品',
name: '旺旺雪饼',
number: '100箱',
price: '25元/袋'
}, {
type: '食品',
name: '双汇火腿',
number: '50箱',
price: '5元/根'
}, {
type: '食品',
name: '毛毛虫面包',
number: '10箱',
price: '3元/袋'
}, {
type: '食品',
name: '阿尔卑斯棒棒糖',
number: '10箱',
price: '0.5元/个'
}, {
type: '食品',
name: '蒙牛酸奶',
number: '20箱',
price: '12.9元/瓶'
}, {
type: '水果',
name: '香蕉',
number: '10斤',
price: '2.5元/斤'
}, {
type: '水果',
name: '葡萄',
number: '20斤',
price: '4元/斤'
}, {
type: '水果',
name: '榴莲',
number: '10斤',
price: '24元/斤'
}, {
type: '水果',
name: '李子',
number: '20斤',
price: '4元/斤'
}];
var csv = '\ufeff';
var keys = [];
tableheader.foreach(function(item) {
csv += '"' + item.coltext + '",';
keys.push(item.colname);
});
csv = csv.replace(/\,$/, '\n');
tablebody.foreach(function(item) {
var _item = {};
keys.foreach(function(key) {
csv += '"' + item[key] + '",';
});
csv = csv.replace(/\,$/, '\n');
});
csv = csv.replace(/"null"/g, '""');
var blob = new blob([csv], {
type: 'text/csv,charset=utf-8'
});
var csvurl = window.url.createobjecturl(blob);
var a = document.createelement('a');
var now = new date();
function to2(num) {
return num > 9 ? num : '0' + num;
}
a.download = '进货信息导出' + now.getfullyear() + to2((now.getmonth() + 1)) + to2(now.getdate()) + to2(now.gethours()) + to2(now.getminutes()) + to2(now.getseconds()) + '.csv';
a.href = csvurl;
document.body.appendchild(a);
a.click();
document.body.removechild(a);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。