您现在的位置是:首页 > 文章详情

vue.js前端实现excel表格导出和获取headers里的信息

日期:2018-09-16点击:492

前段时间写过一篇文章基于element实现后台管理系统,并提到excel表格导出功能,可能描述不是很详细,现在单独整理列出。

后端提供的接口:

// 下载分拣列表 export function getAssormentExport(params) { return request({ url: '/manage/health/assorment/export?ids=' + params, responseType: 'arraybuffer', // 代表内存之中的一段二进制数据 必须加 method: 'get' }) }

vue:点击按钮调用接口

<el-button type="primary" size="mini" @click="addexport()">导出选中</el-button>

script:

 // 导出选中 addexport() { if (this.multipleSelection.length <= 0) { this.$message({ showClose: true, message: '未选中数据', type: 'error' }) return } for (let i = 0; i < this.multipleSelection.length; i++) { this.ids.push(this.multipleSelection[i].id) } // push一个新的数组,存储需要导出信息的ID并传给接口实现数据返回 getAssormentExport(this.ids).then( function(response) { const filename = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1]) || '分拣表.xlsx' this.fileDownload(response.data, filename) // response.data是后端返回的二进制数据流,filename是获取到的导出文件名,获取失败使用默认值 this.ids = [] }.bind(this) ).catch( function(error) { this.$message({ showClose: true, message: error, type: 'error' }) this.ids = [] }.bind(this) ) }, fileDownload(data, fileName) { const blob = new Blob([data], { type: 'application/octet-stream' }) const filename = fileName || 'filename.xlsx' if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(blob, filename) } else { var blobURL = window.URL.createObjectURL(blob) var tempLink = document.createElement('a') tempLink.style.display = 'none' tempLink.href = blobURL tempLink.setAttribute('download', filename) if (typeof tempLink.download === 'undefined') { tempLink.setAttribute('target', '_blank') } document.body.appendChild(tempLink) tempLink.click() document.body.removeChild(tempLink) window.URL.revokeObjectURL(blobURL) } },

查看调用接口返回的信息

5cfd4731e2785b480a22306ec2d4f41acc0.jpg

备注:

1.response返回了包含响应头所带的所有数据,可以使用console.log(response)查看打印数据,但是打印出来的数据只能拿到默认的响应头,这里有个需要注意的地方。

  • Cache-Control

  • Content-Language

  • Content-Type

  • Expires

  • Last-Modified

  • Pragma

如果想让浏览器能访问到其他响应头的话,需要后端在服务器上设置Access-Control-Expose-Headers

Access-Control-Expose-Headers : 'content-disposition'

后端大致写法:

headers.add("Access-Control-Expose-Headers", "Content-Disposition");

这样response.headers['content-disposition'].split(';')[1].split('=')[1] 就能取到接口返回的文件名称了。

2. decodeURI的使用

decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。

实例

在本例中,我们将使用 decodeURI() 对一个编码后的 URI 进行解码:

<script type="text/javascript"> var test1="http://www.w3school.com.cn/My first/" document.write(encodeURI(test1)+ "<br />") document.write(decodeURI(test1)) </script>

输出:

http://www.w3school.com.cn/My%20first/ http://www.w3school.com.cn/My first/
原文链接:https://yq.aliyun.com/articles/640828
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章