✍️ 作者简介: 一个每天中午去打篮球和锻炼的前端开发。
🐈⬛ 两只猫🐱和一只狗的铲屎官🐶
🧣 微博: GuoJ阝阝(fu)
文章目录
- 前言
- 一、实现效果
- 二、实现步骤
- 1、添加导出按钮
- 2、添加点击事件函数
- 3、获取当前时间的方法
- 总结
前言
在后台管理系统中,有时只是线上查看数据还不够,我们经常需要把列表里的数据导出,而需求最多的就是excel文件,因为对于表格型的数据展示最直观。下面我用一个我做过的页面举例。
一、实现效果
二、实现步骤
注意:我需要导出的数据是后端直接提供文档流格式,并非JSON,从浏览器里查看大概是这种:
如果纯前端实现,那就需要插件了,我这里暂时不介绍,可以参考其他大佬的文章。
1、添加导出按钮
代码如下(示例):
<el-button size="mini" type="primary" @click="exportData">导出</el-button>
2、添加点击事件函数
// 导出
exportData() {this.$message.closeAll();this.$message.info("导出中,请稍后~");this.export()
},
export() {// 获取数据用的参数const params = {page: this.page.currentPage,size: this.page.pageSize};// 创建当前时间字符串,生成文件名称时使用const time = this.getCurentTime()// 调用后台接口,获取文件流ExportCheckResult(params).then((res) => {// 转化为blob对象let blob = new Blob([res.data], {type: "application/octet-stream",});let filename = "自定义文件名称" + time + '.xls'// 将blob对象转为一个URLvar blobURL = window.URL.createObjectURL(blob);// 创建一个a标签var tempLink = document.createElement("a");// 隐藏a标签tempLink.style.display = "none";// 设置a标签的href属性为blob对象转化的URLtempLink.href = blobURL;// 给a标签添加下载属性tempLink.setAttribute("download", filename);if (typeof tempLink.download === "undefined") {tempLink.setAttribute("target", "_blank");}// 将a标签添加到body当中document.body.appendChild(tempLink);// 启动下载tempLink.click();// 下载完毕删除a标签document.body.removeChild(tempLink);window.URL.revokeObjectURL(blobURL);this.$message({message: "导出成功~",type: "success",});})
}
3、获取当前时间的方法
getCurentTime() {var date = new Date();//以下代码依次是获取当前时间的年月日时分秒var year = date.getFullYear();var month = date.getMonth() + 1;var strDate = date.getDate();var minute = date.getMinutes();var hour = date.getHours();var second = date.getSeconds();//固定时间格式if (month >= 1 && month <= 9) {month = "0" + month;}if (strDate >= 0 && strDate <= 9) {strDate = "0" + strDate;}if (hour >= 0 && hour <= 9) {hour = "0" + hour;}if (minute >= 0 && minute <= 9) {minute = "0" + minute;}if (second >= 0 && second <= 9) {second = "0" + second;}var currentdate = "_" + year + month + strDate + hour + minute + second;return currentdate;
}
总结
以上就是今天要讲的内容