导出
1.做项目的时候出现了导出功能,就是调后端给的接口然后下载当前列表的数据,应该就是这么个步骤。
2.有一些文档流需要处理,那我就把我的步骤放上来仅供参考,每个人的接口名不一样,根据自己的接口去修改。其他的无脑复制就行。
接口文档里的接口,具体根据后端给的接口去写。
// 导出
export function export(params) {
return request({
url: '/age/export',
method: 'get',
responseType: 'blob', //加入这个流
params,
})
}
vue上添加按钮
<el-button type="warning" plain icon="el-icon-download" :loading="exportLoading" @click="handleExport">导出</el-button>
这就是在调接口的时候把他下载下来
/** 导出按钮操作 */
async handleExport() {
//给他定义里面的参数根据自己的代 有些好像是没带 但是我带了需要的参数就成功了
//具体根据自己来定吧
const requestData = {
archiveTime: this.archiveTime
};
console.log('daochu', requestData);
export(requestData).then((response) => {
if (response) {
//这里设置xlsx的名字根据自己定
const exportFileName = '用户.xlsx';
this.download(response, exportFileName);
}
});
},
download(data, filename) {
// 下载文件
if (data == null) {
} else {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
}
},
导入
其实导出和导入的原理都一样,你传文件然后调接口,刷新列表。
1.首先写接口
//导入
export function upload(data) {
return request({
url: '/age/import',
method:'post',
data: data
})
}
2.然后你在页面添加一个你需要的导入。
<el-col :span="1.5">
<el-upload
ref="upload"
class="filter-item"
action="#"
:before-upload="beforeUpload"
type="primary"
:on-change="uploadExcel"
:show-file-list="false"
:file-list="fileList"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:auto-upload="false"
>
<el-button type="primary" style="margin-left:15px;margin-top:30px;">批量导入</el-button>
</el-upload>
</el-col>
然后要记得在data里return一下你定义的fileList
data(){
return{
fileList:[], //上传的文件列表
}
}
然后再写方法调接口,刷新页面
//上传前校验(其实如果在accept中限制了格式,这一步可有可无---)
beforeUpload(file) {
// 文件类型
console.log(`上传前校验---`, file);
const isType = file.type === 'application/vnd.ms-excel';
const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const fileType = isType || isTypeComputer;
if (!fileType) {
this.$message.error('上传文件只能是xls/xlsx格式!');
}
},
// excel表上传(方法调用在此方法中)
uploadExcel(file, fileList) {
const fileTemp = file.raw;
const fileName = file.raw.name;
const fileType = fileName.substring(fileName.lastIndexOf('.') + 1);
// 判断上传文件格式
if (fileTemp) {
if (fileType === 'xlsx' || fileType === 'xls') {
const formData = new FormData(); //这一步不能变
formData.append('file', file.raw); //这里的file,是你后端的参数,具体看后端写什么
upload(formData).then((res) => {
//调用接口,传递参数。
this.$message({
type: 'success',
message: '导入成功!' //这里是后端返回的提示文字---
}),
this.getList(); // 导入表格之后可以获取导入的数据渲染到页面,此处的方法是获取导入的数据,然后返回到你列表的数据。
});
} else {
this.$message({
type: 'warning',
message: '附件格式错误,请重新上传!'
});
console.log('333');
}
} else {
this.$message({
type: 'warning',
message: '请上传附件!'
});
}
}
在我这里是可以直接用的,有更好的方法,可以和我提出。
欢迎多多指教,多多提出我的问题,不断进步。