场景二:后端返回的是一堆数据,然后自己导出Excel格式文件时:(1)npm下载模块 cnpm install vue-js_vue3下载excel模板调用接口并传递token参数">
赞
踩
<!-- 注:excelUrl绑定的是后端返回的api接口 -->
<el-link :href="excelUrl">
<el-button type="primary" plain>导出数据</el-button>
</el-link>
在src文件夹下=>新建uitls文件夹=>uitls文件夹中新建一个文件export.js封装方法:
export.js中:
// 导出Excel功能 import axios from 'axios' export function expotOut(searchList, pathName, xlsName, url) { // 获取时间,这一步是在下载时文件名带下载日期,例如:用户信息2020-04-27.xls,如无需要可以去掉 let d = new Date() let month = (d.getMonth() + 1) let day = d.getDate() let time = d.getFullYear() + '-' + (String(month).length > 1 ? month : '0' + month) + '-' + (String(day).length > 1 ? day : '0' + day) // 地址 let baseURL = axios.defaults.baseURL // 域名 const PATH = { userList: url // 后台接口地址 } // 参数 let params = '?' for (let key in searchList) { params = params + key + '=' + searchList[key] + '&' } function createObjectURL(object) { return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object) } var xhr = new XMLHttpRequest() var formData = new FormData() xhr.open('get', baseURL + PATH[pathName] + params) // url填写后台的接口地址,如果是post,在formData append参数(参考原文地址) xhr.setRequestHeader('token', localStorage.getItem('token')) xhr.responseType = 'blob' xhr.onload = function(e) { if (this.status === 200) { var blob = this.response // xls文件名称 var filename = `${xlsName}${time}.xls` if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename) } else { var a = document.createElement('a') var url = createObjectURL(blob) a.href = url a.download = filename document.body.appendChild(a) a.click() window.URL.revokeObjectURL(url) } } } xhr.send(formData) }
在所需页面中使用:
<template> <el-button @click="outFile" type="primary" plain>导出</el-button> </template> <script> import { expotOut } from '@/utils/export.js' //引入 //导出 outFile() { expotOut( this.query, // 导出请求参数 'userList', // 后台地址PATH对象的key '用户信息', // 导出文件名字 'clothTestReport/excelExport' //后台url ) }, </script>
(1)npm下载模块
cnpm install vue-json-excel
(2)在main.js中全局引入
import JsonExcel from 'vue-json-excel'
Vue.component('downloadExcel', JsonExcel)
(3)在所需页面中使用
<download-excel class="export-excel-wrapper" :data="json_data" :fields="json_fields" name="远程诊断报告导出.xls">
<el-button round type="primary" size="small">导出数据</el-button>
</download-excel>
json_fields: { "头部-诊断名称": "name", //常规字段 "头部-联系电话": "phone.mobile", //支持嵌套属性 "头部-损坏区域代码": { field: "phone.landline", //自定义回调函数 callback: value => { return `损坏区域代码 - ${value}`; } } }, json_data: [ { name: "损坏的组件一", city: "New York", country: "United States", birthdate: "1978-03-15", phone: { mobile: "1-541-754-3010", landline: "(541) 754-3010" } }, { name: "损坏的组件二", city: "Athens", country: "Greece", birthdate: "1987-11-23", phone: { mobile: "+1 855 275 5071", landline: "(2741) 2621-244" } } ], json_meta: [ [ { " key ": " charset ", " value ": " utf- 8 " } ] ],
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。