【vue3+ts导出数据成表格实现】获取JSON格式数据并且导出表格常用

一、安装xlsx,使用yarn依赖安装的

yarn add xlsx

 二、引入xlsx,vue3引入方式

import * as XLSX from "xlsx";

三、创建一个plugins文件 ,里面创建export.ts文件

import * as XLSX from "xlsx";

export default (
  data: any[],
  sheetName: string = "sheet1",
  fileName: string = "信息.xlsx"
) => {
  const contentSheet = XLSX.utils.json_to_sheet(data);
  
  const workBook = {
    SheetNames: [sheetName], // 指定有序 sheet 的 name
    Sheets: {
      [sheetName]: contentSheet, // 表格数据内容
    },
  };

  return XLSX.writeFile(workBook, fileName); // 向文件系统写出文件
};

四、页面导出按钮

 1、页面布局

<template>
  <div>
    <button @click="exportExcel">导出 Excel</button>
  </div>
</template>

 2、引入封装的导出方法

<script setup lang="ts">
import { reactive, ref } from 'vue'
import * as XLSX from 'xlsx'
import getExport from '../plugins/export'
const testData = [
  {
    name: '社团1号',
    detail: '武汉',
    tel: 154655256452,
    people: '小夫',
    status: '不在状态',
    type: '体育',
  },
  {
    name: '社团2号',
    detail: '北京',
    tel: 154655256452,
    people: '小芙',
    status: '在状态',
    type: '体育',
  },
  {
    name: '社团3号',
    detail: '洛阳',
    tel: 154655256452,
    people: '小夫',
    status: '不在状态',
    type: '体育',
  },
  {
    name: '社团4号',
    detail: '扬州',
    tel: 154655256452,
    people: '小夫',
    status: '不在状态',
    type: '体育',
  },
  {
    name: '社团5号',
    detail: '西安',
    tel: 154655256452,
    people: '小夫',
    status: '不在状态',
    type: '体育',
  },
  {
    name: '社团6号',
    detail: '成都',
    tel: 154655256452,
    people: '小夫',
    status: '不在状态',
    type: '体育',
  },
  {
    name: '社团7号',
    detail: '上海',
    tel: 154655256452,
    people: '小夫',
    status: '不在状态',
    type: '体育',
  },
  {
    name: '社团8号',
    detail: '深圳',
    tel: 154655256452,
    people: '小夫',
    status: '在状态',
    type: '体育',
  },
  {
    name: '社团9号',
    detail: '杭州',
    tel: 154655256452,
    people: '小夫',
    status: '在状态',
    type: '体育',
  },
  {
    name: '社团10号',
    detail: '长沙',
    tel: 154655256452,
    people: '小夫',
    status: '不在状态',
    type: '体育',
  },
]
const excelKeyName = {
  name: '社团名称',
  detail: '详细地址',
  tel: '联系电话',
  people: '联系人员',
  status: '状态',
  type: '类型',
}

const exportExcel = () => {
  const exportdata = testData.map((item) => {
    const newItem: any = {}
    Object.keys(item).forEach((key) => {
      newItem[excelKeyName[key]] = item[key]
    })
    return newItem
  })
  getExport(exportdata)
}
</script>

3、json格式转换成Excel表格自动下载

 实现效果

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值