<template>
<div>
<el-button @click="DownExcel">下载excel</el-button>
</div>
</template>
<script lang="ts" setup>
import { PropType, ref, watch, onMounted } from 'vue'
const jsonData = ref([
{
name: '路人甲',
phone: '123456789',
email: '000@123456.com'
},
{
name: '炮灰乙',
phone: '123456789',
email: '000@123456.com'
},
{
name: '土匪丙',
phone: '123456789',
email: '000@123456.com'
},
{
name: '流氓丁',
phone: '123456789',
email: '000@123456.com'
},
])
onMounted(() => {
// jsonToExcel(jsonData.value, "姓名,电话,邮箱")
})
/**
* 导出 json 数据为 Excle 表格
* @param {json} data 要导出的 json 数据
* @param {String} head 表头, 可选 参数示例:'名字,邮箱,电话'
* @param {*} name 导出的文件名, 可选
*/
const jsonToExcel = (data, head, name = '导出的文件名') => {
let str = head ? head + '\n' : '';
data.forEach(item => {
// 拼接json数据, 增加 \t 为了不让表格显示科学计数法或者其他格式
for (let key in item) {
str = `${str + item[key] + '\t'},`
}
str += '\n'
});
console.log(str)
// encodeURIComponent解决中文乱码
const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
// 通过创建a标签实现
const link = document.createElement("a");
link.href = uri;
// 对下载的文件命名
link.download = `${name + '.csv'}`;
link.click();
}
const DownExcel = () => {
jsonToExcel(jsonData.value, "姓名,电话,邮箱")
}
</script>
<style scoped lang="scss"></style>
json数据转为excel下载
最新推荐文章于 2025-12-25 09:07:35 发布
703

被折叠的 条评论
为什么被折叠?



