一、安装 xlsx
npm install --save xlsx file-saver
二、具体使用整体代码
如果数据格式是这样就用下面的,直接把数据传到 XLSX.utils.json_to_sheet
list: [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
// ...
]
<template><button @click="exportData">导出数据</button>
</template>
import * as XLSX from 'xlsx'methods: {// 导出当前界面列表exportData() {const data = [{"事假": "0.0/5.0","护理假": "0.0/0.0","婚假": "0.0/5.0","申请人":"张三"},{"事假": "0.0/5.0","护理假": "0.0/0.0","婚假": "0.0/5.0","申请人":"李四"}];const dataTitles = ['申请人', '事假', '婚假', '护理假'];const rows = [];for (const item of data) {const entry = {};for (const title of dataTitles) {if (Object.prototype.hasOwnProperty.call(item, title)) {entry[title] = item[title];} else {entry[title] = '';}}rows.push(entry);}const worksheet = XLSX.utils.json_to_sheet(rows)const workbook = XLSX.utils.book_new()XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')const fileBuffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' })this.saveFile(fileBuffer, 'data.xlsx')},// 保存数据并且导出saveFile(buffer, fileName) {const blob = new Blob([buffer], { type: 'application/octet-stream' })const link = document.createElement('a')link.href = URL.createObjectURL(blob)link.download = fileNamelink.click()}}