- 前言,我们在实际项目开发过程中,经常有列表界面,有上传功能,并且支持先下载模板,后上传
- 1.实现效果与前端展示
<form method="post" enctype="multipart/form-data" action="/depart/multi/">
{% csrf_token %}
<div class="form-group">
<input type="file" name="exc">
</div>
<input type="submit" value="上传" class="btn btn-info btn-sm">
<a class="btn btn-info btn-sm" href="/depart/download/">模板下载</a>
</form>
- 2.模板下载,先需要在项目中上传模板
def depart_download(request):
"""下载部门导入模板"""
BASE_DIR = Path(__file__).resolve().parent.parent
media = os.path.join(BASE_DIR, "static","excel")
file_path = os.path.join(media, '部门导入模板.xlsx')
try:
f = open(file_path, "rb")
r = FileResponse(f, as_attachment=True, filename="部门导入模板.xlsx")
return r
except Exception:
raise Http404("down error")
def depart_multi(request):
"""批量上传部门"""
# 获取文件对象
file_object = request.FILES.get("exc") # exc 前端标签的name属性
if not file_object:
return HttpResponse("请上传文件")
# 读取内容,并且保存到数据库
from openpyxl import load_workbook
wb = load_workbook(file_object)
sheet = wb.worksheets[0]
# 循环每一行数据
for row in sheet.iter_rows(min_row=2):
title = row[0].value
exists = models.Department.objects.filter(title=title)
if not exists:
models.Department.objects.create(title=title)
return redirect("/depart/list/")