django上传Excel文件,将文件中的数据批量上传
时间: 2024-05-14 12:14:36 浏览: 128
步骤:
1. 安装openpyxl库, 使用 pip install openpyxl
2. 在model中定义需要上传的字段
```python
class Student(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
gender = models.CharField(max_length=2)
score = models.IntegerField()
```
3. 在视图函数中处理上传文件
```python
def upload_excel(request):
if request.method == 'POST':
excel_file = request.FILES.get('excel_file')
if not excel_file:
return HttpResponseBadRequest('未上传文件')
# 打开Excel文件
workbook = openpyxl.load_workbook(excel_file)
# 获取第一个sheet
sheet = workbook.active
# 获取数据
data = []
for row in sheet.iter_rows(min_row=2):
row_data = []
for cell in row:
row_data.append(cell.value)
data.append(row_data)
# 保存到数据库
for row_data in data:
Student.objects.create(
name=row_data[0],
age=row_data[1],
gender=row_data[2],
score=row_data[3]
)
return HttpResponse('上传成功')
return render(request, 'upload_excel.html')
```
4. 在模板中添加上传表单
```html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="excel_file">
<button type="submit">上传</button>
</form>
```
阅读全文