vue3 - 使用 xlsx 库将数据导出到 Excel 文件

GitHub Demo 地址

在线预览

xlsx是由SheetJS开发的一个处理excel文件的JavaScript库。它可以读取、编写和操作 Excel 文件

安装xlsx

ts 复制代码
npm install xlsx --save

实现一个通过的数据导出工具类

ts 复制代码
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 - worksheet

  XLSX.utils.book_append_sheet(wb, ws, sheetName) // 将工作表添加到工作簿中
  XLSX.writeFile(wb, fileName) // 导出文件
}

示例

ts 复制代码
<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 = data
  const fields = ['name', 'gender', 'age']
  const headers = ['姓名', '性别', '年龄']
  exportExcel(newTableDate, fields, headers, '用户数据.xlsx')
}
</script>

效果图

相关推荐
摩羯座-小齐6 小时前
java excel级联下拉框
java·excel
sheeta19986 小时前
Pinia核心笔记
前端·vue.js·笔记
Cloud_Shy6187 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第九章 Excel 自动化 下篇)
python·数据分析·excel·numpy·pandas
_xaboy1 天前
FormCreate 设计器 v6.3 正式发布:AI 表单助理3.0登场!
前端·vue.js·低代码·开源·表单设计器
马玉霞1 天前
vue web端页面组件展示
前端·vue.js
代码煮茶1 天前
Vue3 权限系统实战 | 从 0 搭建完整 RBAC 权限管理
前端·javascript·vue.js
阳火锅1 天前
💡 告别类名地狱!Tailwind CSS 语义化转换神器来了
前端·css·vue.js
用户125758524361 天前
XYGo Admin 即时通讯与异步任务实战:WebSocket 长连接 + 消息队列驱动后台处理
vue.js
PBitW1 天前
组件封装注意事项
前端·vue.js
城数派1 天前
1958-2024年乡镇的逐月土壤湿度数据
数据库·arcgis·数据分析·excel