1. 创建数据表
class Home(models.Model):
"""首页"""
title = models.CharField(verbose_name="标题", max_length=32)
def __str__(self):
return self.title
2. 创建路由(url)
from bbc_list.views import home_page
rlpatterns = [
path('home/multi/', home_page.home_multi),]
3. 创建视图函数(views-home_page.py)
def home_multi(request):
"""批量上传excel"""
from django.core.files.uploadedfile import InMemoryUploadedFile
from openpyxl import load_workbook
# 1.获取用户上传的文件对象
file_object = request.FILES.get("exc")
print(type(file_object))
# 2.对象传递给openpyxl,由openpyxl读取的文件内容
wb = load_workbook(file_object) # 可以给一个文件路径 / 对象
sheet = wb.worksheets[0]
# 3. 循环获取每一行数据
for row in sheet.iter_rows(min_row=2): # 从第二行开始到最后
print("row=", row)
text = row[0].value # 第一列数据
print("text=", text)
exists = models.Home.objects.filter(title=text).exists()
if not exists:
models.Home.objects.create(title=text)
return redirect("/home/page/") # 跳转回首页
4. 创建html页面
<!--引入公共html-->
{% extends 'one.html' %}
<!--公共占位符内内容-->
{% block content %}
<div class="container">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
批量上传
</div>
<div class="panel-body">
<form method="post" enctype="multipart/form-data" action="/home/multi/">
{% csrf_token %}
<div class="form-group">
<input type="file" name="exc">
</div>
<input type="submit" value="上传" class="btn btn-info btn-sa">
</form>
</div>
</div>
</div>
{% endblock %}
标签:17,title,text,excel,home,上传,page,row
From: https://www.cnblogs.com/kh-1314/p/17059749.html