GitHub Demo 地址
在线预览
xlsx
是由SheetJS开发的一个处理excel文件的JavaScript库。它可以读取、编写和操作 Excel 文件
安装xlsx
npm install xlsx --save
实现一个通过的数据导出工具类
import * as XLSX from 'xlsx'/*** @description: 导出excel* @param {any} dataList* @param {Array} fields* @param {Array} headers* @param {string} fileName 需要加后缀名 eg: 'test.xlsx'* @param {string} sheetName* @return {*}*/
export function exportExcel(dataList: any, fields: Array<string>, headers: Array<string> = [], fileName: string = 'Excel.xlsx', sheetName: string = 'Sheet') {let data = new Array()if (!Array.isArray(dataList)) return console.warn('dataList is not an array type')// if (!Array.isArray(fields)) return console.warn('fields is not an array type')// if (!Array.isArray(headers)) return console.warn('headers is not an array type')data = dataList.map((obj) => {return fields.map((field) => {return obj[field]})})if (headers.length > 0) {data.splice(0, 0, headers)} else {// 将headers设置为英文字段表头data.splice(0, 0, fields)}const ws = XLSX.utils.aoa_to_sheet(data) // 创建工作表const wb = XLSX.utils.book_new() // 创建工作簿// 隐藏表头// let wsrows = [{ hidden: true }]// ws['!rows'] = wsrows // ws - worksheetXLSX.utils.book_append_sheet(wb, ws, sheetName) // 将工作表添加到工作簿中XLSX.writeFile(wb, fileName) // 导出文件
}
示例
<template><el-button @click="exportData"> 导出数据 </el-button>
</template><script setup lang="ts">
import { exportExcel } from '@/utils/exportExcel'const data = [{ name: '张三', gender: '男', age: 18 },{ name: '李四', gender: '女', age: 20 },{ name: '王五', gender: '男', age: 22 }
]const handelExcel = () => {var newTableDate = dataconst fields = ['name', 'gender', 'age']const headers = ['姓名', '性别', '年龄']exportExcel(newTableDate, fields, headers, '用户数据.xlsx')
}
</script>