vue导出数据到excel

安装插件

bash 复制代码
npm install exceljs file-saver

页面代码

vue 复制代码
<template>
  <div class="test-form">
    <div @click="exportData" class="export-btn">导出为excel</div>
  </div>
</template>

<script setup>
// 导出文件
import ExcelJS from 'exceljs'
import FileSaver from 'file-saver'
import { ref } from 'vue'
// 模拟表格数据
const tableData = ref([
  { name: '张三', age: 25, city: '北京' },
  { name: '李四', age: 30, city: '上海' },
  { name: '王五', age: 35, city: '广州' },
  { name: '赵六', age: 40, city: '深圳' },
  { name: '王二', age: 45, city: '成都' },
  { name: '赵四', age: 50, city: '重庆' },
  { name: '王三', age: 55, city: '西安' },
  { name: '王五', age: 60, city: '北京' },
  { name: '赵五', age: 65, city: '天津' },
  { name: '王四', age: 70, city: '大连' },
])

function fileExcel(fileData, fileName = '汇总') {
  // 创建工作簿
  const workbook = new ExcelJS.Workbook()
  // 添加工作表,名为sheet1
  const sheet1 = workbook.addWorksheet('sheet1')
  // 导出数据列表
  const data = fileData
  // 获取表头所有键
  const headers = Object.keys(data[0])
  // 将标题写入第一行
  sheet1.addRow(headers)
  // 将数据写入工作表
  data.forEach(row => {
    const values = Object.values(row)
    sheet1.addRow(values)
  })
  // 导出表格文件
  workbook.xlsx
    .writeBuffer()
    .then(buffer => {
      let file = new Blob([buffer], { type: 'application/octet-stream' })
      FileSaver.saveAs(file, fileName + '.xlsx')
    })
    .catch(error => console.log('Error writing excel export', error))
}

// 导出数据
const exportData = () => {
  // 处理键名(表头格式)
  const processedData = tableData.value.map(item => {
    return {
      姓名: item.name,
      年龄: item.age,
      城市: item.city,
    }
  })
  fileExcel(processedData, '导出数据')
}
</script>

<style scoped lang="scss">
.test-form {
    .export-btn {
      display: inline-block;
      padding: 10px 20px;
      background-color: #007bff;
      color: #fff;
      border-radius: 5px;
      cursor: pointer;
    }
}
</style>
相关推荐
unable code1 天前
磁盘取证-Flying_High
网络安全·ctf·misc·1024程序员节·磁盘取证
unable code2 天前
磁盘取证-ColorfulDisk
网络安全·ctf·misc·1024程序员节·内存取证
unable code3 天前
磁盘取证-[第十章][10.1.2 磁盘取证方法]磁盘取证1
网络安全·ctf·misc·1024程序员节·内存取证
开开心心就好4 天前
免费抽奖工具支持批量导入+自定义主题
linux·运维·服务器·macos·pdf·phpstorm·1024程序员节
开开心心就好8 天前
卸载工具清理残留,检测垃圾颜色标识状态
linux·运维·服务器·python·安全·tornado·1024程序员节
子燕若水9 天前
Facebook reels 运营指南
1024程序员节
尘觉12 天前
创作 1024 天|把热爱写成长期主义
数据库·1024程序员节
写点什么呢13 天前
Word使用记录
word·1024程序员节
开开心心就好13 天前
内存清理工具点击清理,自动间隔自启
linux·运维·服务器·安全·硬件架构·材料工程·1024程序员节
开开心心就好14 天前
内存清理工具开源免费,自动优化清理项
linux·运维·服务器·python·django·pdf·1024程序员节