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>

效果图

相关推荐
卤蛋fg631 分钟前
vxe-table 列拖拽排序与行拖拽排序:让表格布局任意排序
vue.js
技术小甜甜1 小时前
[办公效率] Excel 表格越做越乱,先整理字段、格式还是公式?
数据库·excel·办公效率·数据整理
粉末的沉淀1 小时前
vue:Vite项目中高效管理纯色SVG图标的方案
前端·javascript·vue.js
卤蛋fg61 小时前
vxe-table 列宽与行高拖拽调整:让表格布局极其灵活,拖拽功能非常强大
vue.js
向日的葵0062 小时前
Vue 路由传参的三种方式(三)
vue.js·路由
SunnyDays10112 小时前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
如果超人不会飞2 小时前
TinyVue Checkbox复选框组件使用指南
前端·vue.js
itgather2 小时前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
如果超人不会飞2 小时前
TinyVue Radio单选框组件使用指南
vue.js
鲁班小子2 小时前
Vite resolve.dedupe 使用教程
vue.js·vite