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>
相关推荐
Thanks_ks5 小时前
提示词工程实战:用结构化提示词让大模型输出稳定可控
python·大模型·json·openai·提示词工程·deepseek·系统提示词
程序员大阳9 小时前
副队长Vue3教程(33)--路由懒加载
vue.js·性能优化·vue3·路由·懒加载·速度慢
SEO_juper13 小时前
HTTPS 混合内容检查工具:页面全站 https 了,但还有 http 资源在拖后腿
开发语言·网络协议·http·https·node.js·json·bash
SeanQhl16 小时前
行号会漂,指纹不会:一份可并发编辑的 JSON 清单怎么写
json
用户2986985301416 小时前
在 React 中实现 Excel 与 TXT 格式互转的前端方案
javascript·react.js·excel
BruceVan18 小时前
给 AI 配上 Context7:查文档更准,还更省 token
vue.js·spring boot·ai编程
维爱智VR认知学能18 小时前
VR课程软件版本迭代清单比对:资源哈希与依赖变更提取
json·哈希算法·vr
FYKJ_20101 天前
springboot众创项目团队管理系统94666-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·spark·课程设计
FYKJ_20101 天前
springboot贫困生认定管理系统59009-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·后端·django·课程设计
anyup2 天前
uni-app x 的 Signature 签名板与练字格,一个组件多端支持 App/鸿蒙/H5/小程序
前端·vue.js·uni-app