功能说明
- 页面原来存在查询功能,现新增下载功能,将查询出来的数据导出至Excel表格
- 数据传输格式为json
解决方案
- 前端发起下载请求
- 后台根据查询条件先查询出数据
- 后台将数据生成Excel表格
- 将Excel表格转为base64字符串,放入json,传给前端
- 前端获取json中的文件字符串,开启下载
关键代码
前端请求及返回处理
导出按钮
<el-button type="success" icon="el-icon-download" @click="downloaddata">导出</el-button>
开启下载方法
methods: {
downloaddata() {
// axios发起请求
this.$axios({
method: 'post',
url: '/xxx',
data: {
"age": this.UserAge,
...
}
}).then((res) => {
// 将base64格式文件转为blob供下载
function dataURLtoBlob(base64Str) {
var bstr = atob(base64Str), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// 这里设置的是excel格式的文件,其他格式见后文
return new Blob([u8arr], {
type: "application/vnd.ms-excel" });
}
const blob = dataURLtoBlob(res.data.base64file) // 入参为json中的base64编码文件
const url = window.URL.createObjectURL(blob);
// 开启下载任务
const link