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>

效果图

相关推荐
_codeOH1 天前
Vue 3 vs React 19:框架还在卷,核心原理就这些
前端·vue.js
英勇无比的消炎药1 天前
新手必看玩转TinyRobot一定要避开这些坑
前端·vue.js
英勇无比的消炎药1 天前
别再盲目混用AI组件库和传统组件库差距原来这么大
前端·vue.js
英勇无比的消炎药1 天前
前端提效神器全新AI组件库TinyRobot改写日常开发模式
前端·vue.js
英勇无比的消炎药1 天前
前端提效神器TinyRobot
前端·vue.js
CDwenhuohuo1 天前
uni 背景色渐变 全屏
前端·javascript·vue.js
爱怪笑的小杰杰1 天前
Vue 项目交付第三方开发,如何隐藏核心 JS 源码?
前端·javascript·vue.js
小二·1 天前
Vue 3 组合式 API 进阶实战
前端·javascript·vue.js
不恋水的雨1 天前
easyexcel快速填充大数据量不覆盖后面的行解决方式
java·excel·poi
rising start1 天前
九、vue3 组件通信:全场景详解
前端·vue.js·typescript