需求 :
将数据导出CSV文件
展示:
使用的插件
npm install --save file-saver json2csv
注:使用的是element ui 和 json2csv插件
代码:
(直接复制使用)
<template>
<div>
<div id="app">
<el-row>
<el-button type="text" @click="onExportFile">导出</el-button>
</el-row>
</div>
</div>
</template>
<script>
import { parseTime } from "@/utils/index";
export default {
data() {
return {
cartData: [
{
id: 1,
name: "苹果",
price: 10,
num: 33,
},
{
id: 2,
name: "草莓",
price: 20,
num: 1,
},
{
id: 3,
name: "柠檬",
price: 30,
num: 1,
},
{
id: 4,
name: "香蕉",
price: 40,
num: 1,
},
],
};
},
methods: {
onExportFile() {
let message = "确定导出所选数据?";
let title = "导出数据";
let _this = this;
this.$confirm(message, title, {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
_this.exportFile();
})
.catch(() => {});
},
exportFile() {
const Json2CsvParser = require("json2csv").Parser;
const FileSaver = require("file-saver");
const datetime = Date.now();
let filename = parseTime(datetime, "{y}-{m}-{d}_{h}{i}{s}") + "_log.csv";
//这里是文件名称,封装的日期函数,文件名称是当时的时间
let parser = new Json2CsvParser();
let list = this.cartData.map(e => {
return {
"序号ID": "\t" + e.id,
"名字": e.name,
"单价": "\t" + e.price,
"数量": "\t" + e.num,
}
});
let csvData = parser.parse(list); // list是需要导出的数据
let blob = new Blob(["\uFEFF" + csvData], {
type: "text/plain;charset=utf-8;",
});
FileSaver.saveAs(blob, filename);
this.$alert("数据 " + filename + " 导出成功!", "", {
type: "success",
callback: (action) => {},
});
},
},
};
</script>
封装的函数: “@/utils/index”` 格式化日期
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
如果有报错 解决:‘action’ is defined but never used no-unused-vars
报错原因
因为搭建的vue项目选择了eslint校验规范->就是你定义了某个变量,但是你没有使用它.eslint规范就是你要么不定义,要么定义了就一定得用.
解决方法:
在package.json文件内加入如下代码(保存后重启项目!!!)
"rules": {
"generator-star-spacing": "off",
"no-tabs":"off",
"no-unused-vars":"off",
"no-console":"off",
"no-irregular-whitespace":"off",
"no-debugger": "off"
}