准备工作 - 下载 xlsx
npm install xlsx
下面直接上代码👇
<template>
<div @click="handleExport">导出excel</div>
</template>
<script setup lang="ts">
import * as XLSX from 'xlsx'
const handleExport = () => {
const tableData = [
{ name: '张三', age: 18, gender: '男' },
{ name: '李四', age: 20, gender: '女' },
{ name: '王五', age: 22, gender: '男' }
]
// 处理后的数据
const headers = ['姓名', '年龄', '性别']
const data = tableData.map(item => Object.values(item)) // [['张三', 18, '男'], ['李四', 20, '女'], ['王五', 22, '男']]
// 导出excel
const workbook = XLSX.utils.book_new()
const sheet = XLSX.utils.aoa_to_sheet([headers, ...data]) // [['姓名', '年龄', '性别'], ['张三', 18, '男'], ['李四', 20, '女'], ['王五', 22, '男']]
// 一个 workbook 允许添加多个 sheet,即可以同时创建多个表
XLSX.utils.book_append_sheet(workbook, sheet, '表单1的名称')
XLSX.writeFile(workbook, 'excel的名称.xlsx')
}
</script>