<template>
<div>
<button id="btn" @click="handlerClick">下载</button>
</div>
</template>
<script>
export default {
data() {
return {
header: [
{ key: "order", title: "序号" },
{ key: "name", title: "姓名" },
{ key: "age", title: "年龄" },
{ key: "height", title: "身高" },
{ key: "address", title: "地址" },
],
content: [
{
order: 1,
name: "Abby",
age: 23,
height: 168,
address: "北京,中关村",
},
{
order: 2,
name: "Leo",
age: 28,
height: 183,
address: "上海,陆家嘴",
},
{
order: 3,
name: "Alen",
age: 35,
height: 178,
address: "深圳,南山区",
},
{
order: 4,
name: "Daisy",
age: 27,
height: 160,
address: "广州,天河区",
},
]
}
},
methods: {
handlerClick(){
this.downloadCsv(this.header,this.content,'人员信息表')
},
/**
* @description 纯前端实现将表格数据导出为csv格式文件
* @param {Array} headers 表格头配置项,headers中的key值与data中每一个item的属性名一一对应
* @param {Array} data 表格数据
* @param {String} fileName 导出的文件名称
*/
downloadCsv(header, data, fileName = "导出结果.csv") {
if (!header || !data|| !Array.isArray(header) || !Array.isArray(data) || !header.length || !data.length) {
return;
}
var csvContent = 'data:text/csv;charset=utf-8,\ufeff';
const _header = header.map(h => h.title).join(",");
const keys = header.map(item => item.key);
csvContent += _header + '\n';
data.forEach((item, index) => {
let dataString = '';
for (let i = 0; i < keys.length; i++) {
dataString += item[keys[i]] + ',';
}
csvContent += index < data.length ? dataString.replace(/,$/, '\n') : dataString.replace(/,$/, '');
});
const a = document.createElement('a');
a.href = encodeURI(csvContent);
a.download = fileName;
a.click();
window.URL.revokeObjectURL(csvContent);
}
}
}
</script>
纯前端实现下载excel功能
于 2022-11-17 11:19:54 首次发布