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>
相关推荐
Agome995 分钟前
linux面试题
java·开发语言·excel
快乐肥宅_20 分钟前
Vue2与Vue3模板编译器对比分析
vue.js
杀死一只知更鸟debug36 分钟前
vue2,vue3,vue3 + vite 动态加载图片的方式
前端·javascript·vue.js
失去妙妙屋的米奇1 小时前
Python库与Excel
开发语言·python·excel
winfredzhang1 小时前
将 Markdown 表格结构转换为Excel 文件
python·excel·markdown
Jenlybein2 小时前
学完 Vue3 记不牢?快来看这篇精炼Vue3笔记复习一下 [ Route 篇 ]
前端·vue.js
页面魔术2 小时前
[译]专访尤雨溪: 2025年有什么计划?
前端·vue.js·vite
糯糯机器3 小时前
天啦噜,Vue生命周期加上async并不会阻塞子组件的加载
vue.js
小old弟3 小时前
vue3模板中ref的实现原理
前端·vue.js
Moshow郑锴4 小时前
SpringBoot3+EasyExcel通过WriteHandler动态实现表头重命名
spring·excel·导出·阿里巴巴·easyexcel·speadsheet