vue3 excel 导出功能
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
免费下载资源
·
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>
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>
GitHub 加速计划 / vu / vue
207.55 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:3 个月前 )
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 5 个月前
e428d891
Updated Browser Compatibility reference. The previous currently returns HTTP 404. 6 个月前
更多推荐
已为社区贡献3条内容
所有评论(0)