def test_test(request):
data = xlrd.open_workbook('execl表所在的文件路径') # 读取数据
# print(date.nsheets) #查看excel里面有几张表
table = data.sheet_by_index(0) # 取到第一张表单
# name=date.sheet_names() #获取所有表单
# print(name)
t = table.nrows # 读取表的行数
# print(t)
t1 = table.ncols # 读取表的列数 返回7列
# print(t1)
company = []
for i in range(table.nrows):
if i.__ne__(0):#__ne__ 的意思是 特定的比较X!=Y
rows = str(table.row_values(i)) # 一行一行的读
# print(rows) #输出每一行的数据
# clos = str(table.col_values(i)) #一列一列的读
row = eval(rows)
# name = row[1]
# print(name) #输出每一行索引为1 的数据
S_id = row[0]
S_name = row[1]
name = row[2]
money = row[3]
proportion = row[4]
bank = row[5]
account = row[6]
t1 = model里定义类名称.objects.filter(筛选条件).values() #在数据库里查找excel表里的内容
print(t1) # 输出内容
testdata.objects.create(S_id=S_id, S_name=S_name, name=name,
money=money, proportion=proportion, bank=bank, account=account)
if t1: #如果内容存在就更新内容
t1.update(S_id=S_id, S_name=S_name, name=name,
money=money, proportion=proportion, bank=bank, account=account) # 向数据库更新excel表里面更新的数据
else: #如果内容不存在就向数据库里增加内容
testdata.objects.create(S_id=S_id, S_name=S_name, name=name,
money=money, proportion=proportion, bank=bank, account=account)
if money > 5000: # 按条件增加数据
if t1:
t1.update(S_id=S_id, S_name=S_name, name=name,
money=money, proportion=proportion, bank=bank, account=account) # 向数据库更新excel表里面更新的数据
else:
testdata.objects.create(S_id=S_id, S_name=S_name, name=name,
money=money, proportion=proportion, bank=bank, account=account)
if money<=6666:
testdata.objects.filter(money=money).delete() #删除过滤条件里面的内容
testdata.objects.filter(name='莫干那').update(name='莫甘娜')
testdata.objects.filter(S_id='006').delete()
company.append(rows)
return JsonResponse(company, json_dumps_params={'ensure_ascii': False}, safe=False)
Django实现excel导入数据库(超详细)
最新推荐文章于 2024-09-26 09:57:02 发布