1.安装 xlsx 库
npm install xlsx
2.创建导出函数
src/utils/excelUtils.js
import * as XLSX from 'xlsx';
const exportToExcel = (fileName, datas, sheetNames) => {
// 创建工作簿
const wb = XLSX.utils.book_new()
for (let i = 0; i < datas.length; i++) {
let data = datas[i];
let sheetName = sheetNames[i];
// 创建工作表
let ws = XLSX.utils.json_to_sheet(data)
// 将工作表放入工作簿中
XLSX.utils.book_append_sheet(wb, ws, sheetName)
}
// 生成文件并下载
XLSX.writeFile(wb, fileName)
}
export default exportToExcel;
3.在组件中调用导出函数
<template>
<div>
<el-button @click="exportExcel">导出 Excel</el-button>
</div>
</template>
<script lang="ts">
import exportToExcel from '@/utils/excelUtils';
const exportExcel = () => {
const data2 = [
{ name: 'Alice', age: 25, occupation: 'Engineer' },
{ name: 'Bob', age: 30, occupation: 'Designer' },
{ name: 'Carol', age: 28, occupation: 'Developer' }
];
const data3 = [
{ name2: 'Alice', age: 27, occupation: 'Engineer' },
{ name2: 'Bob', age: 31, occupation: 'Designer' },
{ name2: 'Carol', age: 29, occupation: 'Developer' }
];
exportToExcel('user_data.xlsx', [data2, data3], ['Sheet1', 'Sheet_data3']);
};
export default {
methods: {
exportExcel
}
};
</script>
文章来源:https://www.toymoban.com/news/detail-637318.html
4.补充: 列名替换成中文
<template>
<div>
<el-button @click="exportExcel">导出 Excel</el-button>
</div>
</template>
<script lang="ts">
import exportToExcel from '@/utils/excelUtils';
const exportExcel = () => {
const data2 = [
{ name: 'Alice', age: 25, occupation: 'Engineer' },
{ name: 'Bob', age: 30, occupation: 'Designer' },
{ name: 'Carol', age: 28, occupation: 'Developer' }
];
const data3 = [
{ name2: 'Alice', age: 27, occupation: 'Engineer' },
{ name2: 'Bob', age: 31, occupation: 'Designer' },
{ name2: 'Carol', age: 29, occupation: 'Developer' }
];
const changeFieldName = { // 替换列名的对应关系
name: '名称',
name2: '名称2',
age: "年龄",
occupation: "职业"
}
let dealcolumn = function (dataIn, fieldNameMap) { // 替换写表的列名
dataIn.forEach((item) => {
for (const field in fieldNameMap) {
const value = fieldNameMap[field];
if (item[field] != null) {
item[value] = item[field]
delete item[field];
}
}
})
};
dealcolumn(data2, changeFieldName);
dealcolumn(data3, changeFieldName);
exportToExcel('user_data.xlsx', [data2, data3], ['Sheet1', 'Sheet_data3']);
};
export default {
methods: {
exportExcel
}
};
</script>
文章来源地址https://www.toymoban.com/news/detail-637318.html
到了这里,关于vue3 excel 导出功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!