vue页面中,通过接口获取json返回值,并导出到Excel中;

vue页面中,通过接口获取json返回值,并导出到Excel中;

注意事项:

  • 1、json中的key翻译成对应标题;
  • 2、过滤掉json中不需要的字段;

1、接口返回的json:

css 复制代码
{
    "errcode": 0,
    "data": {
        "total": 3,
        "items": [
            {
                "hospital": "医院1",
                "department": "心内科",
                "num": 10
            },
            {
                "hospital": "医院2",
                "department": "心内科",
                "num": 4
            },
            {
                "hospital": "医院3",
                "department": "体检",
                "num": 3
            }
        ]
    },
    "errmsg": "成功"
}

2、安装 xlsx 库:

css 复制代码
npm install xlsx

3、定义方法:

css 复制代码
<template>
  <div>
    <button @click="handleExportXls">导出Excel</button>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  data() {
    return {
        titleMapping: { // key映射成对应的title
	        hospital: '医院',
	        department: '科室',
	        num: '数量',
	      },
	    excludedKeys: ['num'], // 需要过滤的key
    };
  },
  methods: {
     handleExportXls() {
      console.log('导出到Excel')

      try {
        const res= await axios.get('YOUR_API_URL');
        if (res.errcode == 0) {
          console.log(res.data.items)
          var chartList = res.data.items
          console.log('数据长度:' + chartList.length)

          const transformedData = res.data.items.map((item) => {
            const transformedItem = {}

            for (const key in item) {
              this.excludedKeys.forEach((key) => delete item[key]) //过滤掉不需要的key

              if (key in this.titleMapping) {
                //key映射成对应的标题
                transformedItem[this.titleMapping[key]] = item[key]
              }
            }
            return transformedItem
          })

          this.exportToExcel(transformedData)
        }
      } catch (error) {
        console.error(error);
      }
    },
    exportToExcel(listData) {
      const worksheet = XLSX.utils.json_to_sheet(listData)
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

      const excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
      })

      const data = new Blob([excelBuffer], { type: 'application/octet-stream' })
      const fileName = '报表.xlsx'

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        // For IE
        window.navigator.msSaveOrOpenBlob(data, fileName)
      } else {
        // For other browsers
        const url = window.URL.createObjectURL(data)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        link.click()
        window.URL.revokeObjectURL(url)
      }
    },
  }
};
</script>
相关推荐
程序员清风7 小时前
CSV、Excel 与数据库数据读取实践
数据库·oracle·excel
liangshanbo12158 小时前
高级前端面试题:package.json 常见字段
前端·json
泡海椒11 小时前
JQuick-Excel JContext 与 trans 实战:将字典值带入行转换
excel
大纽耶耶11 小时前
我把 YOLO 训练做成了网页版:需求设计与技术选型
vue.js
大纽耶耶11 小时前
开发 YOLO 训练管理平台的 23 个实践教训
vue.js
Maynor在掘金11 小时前
1.9 万 Star 的 Hypit:让 AI Agent 帮你“一键复刻”爆款视频,保姆级上手教程
vue.js·github
ym hyd 11111 小时前
门诊挂号系统源码 Java+SpringBoot+Vue3 前后分离
java·vue.js·spring boot·毕设
斯内普吖12 小时前
(开源)宠物饲养系统实战指南 基于 Java + SSM + Vue + MySQL
java·vue.js·mysql·开源·宠物
可乐鸡翅yeah_13 小时前
新手梳理:HLS 线上问题,哪些该提给 CDN,哪些该找后端切片服务
开发语言·前端·javascript·vue.js·网络协议·http·m3u8在线
Q264336502313 小时前
【有源码】基于SpringBoot+Vue的博物馆展览与服务一体化平台-java博物馆数字化展品展示与交互平台设计
java·vue.js·spring boot·spring·毕业设计·javaweb·课程设计