一、excel文件上传
1、html代码:
<el-button size="mini" :plain="true" class="file-box" type="button">
导入
<input id="up" ref="file" type="file" class="file-btn" @change="inputCustomProduct">
</el-button>
css样式:
.file-box{
position: relative;
}
.file-btn{
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
outline: none;
background-color: transparent;
filter:alpha(opacity=0);
-moz-opacity:0;
-khtml-opacity: 0;
opacity: 0;
}
2、导入excel文件
inputCustomProduct(e){
//声明一个FormDate对象
let formData = new FormData();
let file = e.target.files[0]
//把文件信息放入对象中
formData.append( "excelFile", file);
// let params = new URLSearchParams(formData) //当请求没有转换成formData时使用
if(file.type == "application/vnd.ms-excel" || file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
this.$ajax({
method: "post",
url: "",
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then( res => {
if(res.code === 200){
this.$message({
message: "导入成功",
type: "success"
})
}else {
this.$message({
message: "导入失败",
type: "error"
})
}
})
}else {
this.$message({
message: "请选择excel文件!",
type: "error"
})
}
//此处必须将控制导入的input值进行置空,否则不会触发change事件,会导致同一个文件不能二次导入
document.getElementById('up').value = null;
},
3、导出excel
outputCustomProduct() {
this.$ajax({
method: "",
url: "",
params: {
},
responseType: 'blob'
}).then(res => {
console.log(res)
//调用成功,在html中创建一个a元素
let aTag = document.createElement('a');
//创建一个blob对象
let blob = new Blob([res], {
//Excel文件版本
type: "multipart/form-data;charset=utf-8", //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
});// 这个content是下载的文件内容,自己修改
aTag.download = '订单导入模板.xls';// 下载的文件名
aTag.href = window.URL.createObjectURL(blob); //创建一个URL对象
aTag.click();
document.body.removeChild(aTag)
window.URL.revokeObjectURL(blob); //释放URL对象
})
},