el-upload上传excel文件
时间: 2025-01-18 11:50:39 浏览: 46
### 使用 `el-upload` 组件上传 Excel 文件
#### 前端 Vue 页面设置
为了使用 `el-upload` 组件来上传 Excel 文件,在前端页面中可以按照如下方式定义该组件:
```html
<template>
<div>
<!-- 定义 el-upload 组件 -->
<el-upload
ref="upload1"
action="#"
:limit="1"
accept=".xls,.XLS,.xlsx,.XLSX"
:auto-upload="false"
:file-list="fileList"
class="upload-formdata"
@change="handleChange"
>
<el-button type="primary">
<i class="fa fa-upload"></i> 导入
</el-button>
</el-upload>
<!-- 提交按钮用于触发上传操作 -->
<el-button type="success" @click="submitUpload">提交</el-button>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [], // 存储已选中的文件列表
};
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList.slice(-1); // 只保留最新的一个文件
},
submitUpload() {
const formData = new FormData();
if (this.fileList.length === 0) {
alert('请选择要上传的文件');
return;
}
formData.append('file', this.fileList[0].raw);
fetch('/api/upload/excel', { // 后端API路径需根据实际情况调整
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
}
};
</script>
```
此部分代码展示了如何通过 `@change` 和自定义方法 `handleChange()` 来管理文件的选择状态,并利用表单数据对象 (`FormData`) 将选定的文件发送给服务器[^1]。
#### 后端接收逻辑
对于后端来说,当接收到带有 Excel 文件的数据请求时,应该能够正确解析并处理这些文件。这里给出 Python Flask 的简单例子作为说明:
```python
from flask import request, jsonify
import pandas as pd
@app.route('/api/upload/excel', methods=['POST'])
def upload_excel():
file = request.files.get('file')
try:
df = pd.read_excel(file.stream)
excel_data_list = []
for index, row in df.iterrows():
record = {'手机号码': str(row['手机号码'])}
excel_data_list.append(record)
# 这里可以根据业务需求进一步处理excel_data_list
return jsonify({
"status": "success",
"message": f"{len(excel_data_list)} records processed.",
"data": excel_data_list
}), 200
except Exception as e:
return jsonify({"error": str(e)}), 400
```
这段Python脚本实现了对接收的Excel文件读取以及转换成JSON格式返回的功能[^3]。
阅读全文
相关推荐


















