使用Element Plus和xlsx库实现Excel文件导出功能


学习如何使用Element Plus和xlsx库在Web应用程序中实现Excel文件导出功能,通过封装代码和注册全局组件,实现一键导出数据到Excel文件的功能。

安装xlsx

c# | 复制yarn add xlsx

封装代码

html | 复制1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<template>
    <el-button style="float: right; padding: 3px 5px" type="primary" @click="exportData">一键导出数据</el-button>
</template>

<script setup lang="ts">
import * as XLSX from 'xlsx'

const props = defineProps({
    //传入的数据
    data: {
        type: Array,
        required: true
    },
    //传入的表格名字
    title: {
        type: String,
        required: true
    }
})
const exportData = (): void => {
    //1.创建一个excel工作簿
    let excelBook = XLSX.utils.book_new()
    //2.创建一个excel工作表
    let excelWorkSheet = XLSX.utils.json_to_sheet(props.data)
    //3.将excel工作表添加到excel工作簿中
    XLSX.utils.book_append_sheet(excelBook, excelWorkSheet)
    //4.下载excel文件
    XLSX.writeFile(excelBook, props.title + '.xlsx', {
        bookType: 'xlsx',
    })
}
</script>

注册全局组件

main.js

js | 复制1
2
import ExportTable from "@/components/ExportTable.vue";
app.component("ExportTable", ExportTable); //全局注册组件

使用

html | 复制1
2
<!-- 导出用户表 -->
<ExportTable :data="tableData" title="导出用户表" />


扫描二维码,在手机上阅读

路由守卫实现

ElementPlus即将在版本 3.0.0中弃用type.text

评 论