Django admin后台上传excel,并保存数据到数据库
models.py
class ImportFile(models.Model):
file = models.FileField(upload_to='media')
admin.py
from .models import ImportFile
@admin.register(ImportFile)
class ImportFileAdmin(admin.ModelAdmin):
list_display = ('file', )
# 重写save_model
def save_model(self, request, obj, form, change):
res = super(ImportFileAdmin, self).save_model(request, obj, form, change)
import_user(self, request, obj, change)
return res
appmul下新建utils.py 内容如下
from openpyxl import Workbook, load_workbook
import datetime
from birthapp import models
def import_user(self, request, obj, change):
# 拿到上传文件的obj最相应逻辑处理,obj相当于 models.objects.表.get(id=id)
print(obj.file.path)
wb = load_workbook(filename=obj.file.path)
E = wb.active
print("E:", type(E))
# ws = wb.get_sheet_names()
# ws = wb.get_sheet_by_name(ws[0])
# print("ws:", ws, type(ws))
print("行数:", E.max_row)
print("列数:", E.max_column)
# a = str(E.cell(row=2, column=5).value) # 将excel中 1行2列 对应的数据传给a
# print(a)
# 找到第五列的所有手机号
for row in range(3, E.max_row+1):
phone = E.cell(row=row, column=5).value
if not phone:
continue
birth = E.cell(row=row, column=6).value
if birth:
birth_flag = 1
else:
birth = E.cell(row=row, column=7).value
print("农历:", birth, type(birth))
if birth:
birth_flag = 2
else:
continue
print("第n行数:", row, "手机号:", phone, "生日:", birth, "标记", birth_flag)
try:
month = birth.split("月")
day = month[1].replace("日", '')
birth = datetime.date(2021, int(month[0]), int(day))
models.Employee.objects.filter(mobile=phone).update(birth=birth, birth_flag=birth_flag)
except Exception as e:
print("error:", e)