Vue3 上传 Excel 文件
一、安装 axios
1.1 安装 axios
1.2 安装 vue-axios
1.3 全局引入 axios
import axios from 'axios'
const app = createApp(App)
// 引入
app.config.globalProperties.$axios = axios二、编写上传界面
<template>
<el-upload
ref="uploadRef"
class="upload-demo"
action="/uploadExcel"
accept=".xls,.xlsx,.csv"
:on-success="handleFileUploadSuccess"
:on-change="handleChange"
:before-upload="handleBeforeUpload"
:auto-upload="false"
:limit="5"
:file-list="fileList"
>
<template #trigger>
<el-button type="primary">选择 Excel 文件</el-button>
</template>
<el-button class="ml-3" type="success" @click="submitUpload">
生成
</el-button>
</el-upload>
</template>
export default {
name: 'App',
components: {
HelloWorld
},
data(){
return {
fileList: [], // 定义一个空数组
}
},
methods: {
/**
* 上传之前的处理
* @returns {boolean}
*/
handleBeforeUpload(rawFile) {
return true;
},
/**
* 上传成功的处理
*/
handleFileUploadSuccess(file){
},
/**
* 提交上传的文件
*/
submitUpload(){
// 判断是否有文件再上传
if (this.fileList.length === 0) {
return this.$message.warning('请选取文件后再上传')
}
// 下面的代码将创建一个空的 FormData 对象:
const formData = new FormData();
// 参数的键名为 'file'
this.fileList.forEach((file) => {
formData.append('file', file.raw);
})
// 通过 axios 进行上传
// uploadExcelFile 后端处理的路径
this.params = formData;
axios({
method: 'post',
url: 'http://localhost:8080/uploadExcelFile',
data: this.params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
},
/**
* 过滤上传的文件类型
*/
handleChange(file, fileList){
if (!/\.(xlsx|xls|XLSX|XLS|csv)$/.test(file.name)) {
this.$message({
type: 'warning',
message: '上传文件只能为 Excel 文件!'
})
this.fileList = []
return false
}
// 手动上传需要保存 file.raw
this.file = file.raw
}
}
}
</script>三、后端处理 Post 请求
3.1 后端处理函数
3.2 添加 dependency
3.3 创建 Excel 文件的实体类 ExcelEntity.java
3.4 创建 ExcelEntityListener.java 监听器
3.5 创建 UploadDao.java
四、结果展示
4.1 本地 Excel 测试数据
订单号
外部订单号
订单商品状态
交易成功时间
商品名称
商品类型
商品类目
商品规格
规格编码
商品编码
商品单价
商品成本价
商品优惠方式
商品优惠后价格
商品数量
商品金额小计
店铺优惠(分摊)
商品实际成交金额
商品抵用积分数
商品留言
收货人/提货人
收货人手机号/提货人手机号
收货人省份
收货人城市
收货人地区
详细收货地址/提货地址
买家备注
商品发货状态
商品发货方式
商品发货物流公司
商品发货物流单号
发货员工
商品发货时间
商品退款状态
商品已退款金额
商家订单备注
入住时间
4.2 上传
4.3 log 输出的 Excel 数据
最后更新于
