Django中从本地上传excel⽂件并将数据存储到数据库Django中从本地上传excel⽂件并将数据存储到数据库
⼀、前端界⾯
<div class="page-container">
<form action="{% url 'basic:uploadGrade' %}" method="post"
enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" id="filename">
<button class="btn btn-primary-outline radius size-S" type="submit">提交</button>
</form>
</div>
⼆、views中
def uploadGrade(request):
'''
班级信息导⼊
:param request:
:return:
'''
hod == 'POST':
f = ('file')
excel_type = f.name.split('.')[1]
if excel_type in ['xlsx','xls']:
# 开始解析上传的excel表格
wb = xlrd.open_workbook(filename=None,file_ad())
table = wb.sheets()[0]
rows = ws # 总⾏数
try:
with transaction.atomic(): # 控制数据库事务交易
for i in range(1,rows):
rowVlaues = w_values(i)
major = models.TMajor.objects.filter(majorid=rowVlaues[1]).first()
models.ate(gradeid=rowVlaues[0],major=major,gradename=rowVlaues[2],memo=rowVlaues[3])
except:
<('解析excel⽂件或者数据插⼊错误')django前端模板
return render(request,'bg/success.html',{'message':'导⼊成功'})
else:
<('上传⽂件类型错误!')
return render(request,'bg/failed.html',{'message':'导⼊失败'})
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论