Vue学习随笔二 —— 前端文件导出
后端接口返回的文件流下载为 excel 文件
一、axios 导出接口文件流
1、接口封装
output(){
// 接口参数
const params = {param1: this.param1, param2: this.param2, ...}
console.log("params==", params)
axios({
method:'POST',
url:'http://127.0.0.1:8081/api/xxx/exportApi', // 接口地址
data: params, // 参数写在请求 body中
// params: params, // 请求参数直接拼接在 url 后面, 两种请求方式根据接口选择
responseType: 'blob',
headers: {
Authorization : localStorage.token, // 一般token存储在localStorage中,从 loacalStorage 中获取 token
}
}).then( res => {
const file = new Blob([res.data], { type: "application/vnd.ms-excel" })
const url = URL.createObjectURL(file)
const a = document.createElement("a")
a.href = url
a.download = "xxx详情信息.xls"
a.click()
})
},
2、调用方法
<el-button class="output" size="mini" @click="output">列表导出</el-button>
二、 直接导出表格数据
1、安装插件
npm i vue-json-excel
2、页面引入组件
<download-excel
class = "export-excel-wrapper"
:data = "exportData"
:fields = "json_fields"
name = "xxxx 详情列表.xls">
<el-button type="primary" size="mini" >列表导出</el-button>
</download-excel>
3、获取导出数据
data(){
return {
exportData: [],
json_fields:{
字段名1: "接口返回字段1",
字段名2: "接口返回字段2",
字段名3: "接口返回字段3",
字段名4: "接口返回字段4",
},
json_meta: [
{
"key": "charset",
"value": "utf-8"
}
]
}
},
methods: {
getData(){
const params = {param1: this.param1, param2: this.param2, ...}
// 后端接口
getDatalList(params).then( res => {
console.log("getDatalList res", res)
this.exportData = res.data
})
},
}