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>
相关推荐
浪九天39 分钟前
Vue 不同大版本与 Node.js 版本匹配的详细参数
前端·vue.js·node.js
尚学教辅学习资料1 小时前
基于SpringBoot+vue+uniapp的智慧旅游小程序+LW示例参考
vue.js·spring boot·uni-app·旅游
_风中无我。1 小时前
Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。
java·spring·json
IT、木易2 小时前
跟着AI学vue第五章
前端·javascript·vue.js
薛定谔的猫-菜鸟程序员2 小时前
Vue 2全屏滚动动画实战:结合fullpage-vue与animate.css打造炫酷H5页面
前端·css·vue.js
春天姐姐3 小时前
vue3项目开发总结
前端·vue.js·git
whisperrr.5 小时前
【JavaWeb12】数据交换与异步请求:JSON与Ajax的绝妙搭配是否塑造了Web的交互革命?
前端·ajax·json
烂蜻蜓6 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app
谢尔登7 小时前
Vue 和 React 的异同点
前端·vue.js·react.js
子非衣10 小时前
MySQL修改JSON格式数据示例
android·mysql·json