Django读取EXcel
前端重要代码
<div class="row"> <div> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="file_obj"> <!-- <input type="text" name="project_pk" hidden value="{{ project_pk }}"> --> <input type="submit" value="提交"> </form> <span style="color: red">{{ error }}</span> </div> </div> {% endblock %}
重点是form表前要有enctype="multipart/form-data"
字段标识,不然Django后台无法识别这个是文件类型的数据;上传文件的input字段的type类型要是file类型。
再来看views视图处理:
from django.shortcuts import render, redirect, HttpResponse from django.db import transaction def import_case(request, pk): """ 导入Excel数据,pk是所属项目的pk """ if request.method == 'POST': try: with transaction.atomic(): # 事物 # project_pk = request.POST.get("project_pk") # 数据库使用字段 excel = request.FILES.get('file_obj') book = xlrd.open_workbook(filename=None, file_contents=excel.read()) sheet = book.sheet_by_index(0) title = sheet.row_values(0) for row in range(1, sheet.nrows): print(sheet.row_values(row)) # 这里取出来每行的数据,就可以写入到数据库了 return HttpResponse('OK') except Exception as e: print(e) return render(request, 'import_case.html', {"project_pk": pk, "error": "上传文件类型有误,只支持 xls 和 xlsx 格式的 Excel文档"}) return render(request, 'import_case.html', {"project_pk": pk, "error": ""})
see also:Django上传并读取Excel