其实是很简单的,上传代码比较多是因为我的上传有把数据加到数据库中,以及一些业务逻辑
def download(request):
"""
黑名单的模板下载
:param request:
:return:
"""
def file_contter(file_name):
with open(file_name,'rb') as f :
c = f.read()
return c
the_file_name = "/home/mumu/bank_project/dowmload/test.xls"
# 这里创建返回
response = StreamingHttpResponse(file_contter(the_file_name)) # 这里创建返回
response['Content-Type'] = 'application/vnd.ms-excel'
response['Content-Disposition'] = 'attachment;filename="template.xls"'
# print(file_iterator(the_file_name))
return responsefrom django.http import StreamingHttpResponse

优化
def big_file_download(request):
# do something...
   def file_iterator(file_name, chunk_size=512):
  with open(file_name) as f:
    while True:
      c = f.read(chunk_size)
      if c:
        yield c
      else:
        break
  the_file_name = "big_file.pdf"
  response = StreamingHttpResponse(file_iterator(the_file_name))
  response['Content-Type'] = 'application/octet-stream'
  response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
  return response

将excel的文件上传,并获取每行及每列信息加入数据库

def upload(request):

    # 上传文件
if request.method == 'POST':
f = request.FILES.get('my_file',None)
type_excel = f.name.split('.')[1]
if 'xls' == type_excel or 'xlsx' == type_excel:
# 解析上传的文件
wb = xlrd.open_workbook(filename=None,file_contents=f.read(),formatting_info=True)
# 提取表格内容
table = wb.sheets()[0]
# # 获取行数
nrows = table.nrows
if nrows <= 1:
return HttpResponse('请填写文件')
# # 获取列数
ncols = table.ncols
# 所有数据放在一个总列表中
all_list = []
for r in range(1,nrows):
# 一行数据放在一个列表中
one_list = []
for c in range(1,ncols):
value = table.row_values(r)[c]
# 判断未填写的是否是有效和失效日期
if (value == ""):
if (c != 3 and c != 4):
print(c,type(c),value)
div = "第{}行第{}列未填写,请重新填写".format(r,c)
return render(request,'upload.html',locals())
one_list.append(value)

all_list.append(one_list)
# 数据库更新或添加
"""需要添加事务,用于回滚"""
# transaction.atomic()
# save_id = transaction.savepoint()
try:
# 创建事务,当有信息填错时回滚,
i = 0
with transaction.atomic():
for n in range(len(all_list)):
i+=1
# 以id_name查找用户
find = all_list[n][1]
user = BlackList.objects.filter(id_name=find)
# 行里每列的值
u_name = all_list[n][0]
u_id_name = all_list[n][1]
u_start_data = datetime.now().strftime('%Y-%m-%d') if all_list[n][2] == '' else all_list[n][2]
u_end_data = "6666-11-01" if all_list[n][3] == '' else all_list[n][3]
u_mark = all_list[n][4]
u_type = all_list[n][5]
if len(user) == 0:
BlackList.objects.create(name=u_name,id_name=u_id_name,start_data=u_start_data,end_data=u_end_data,mark=u_mark,type=u_type)
# BlackList.objects.create(name='mumu',id_name='234657865456789876',start_data='2423-01-01',end_data='6666-11-11',mark='对公',type='酒驾')
# print('---------------')
else:
user[0].name = u_name
user[0].id_name = u_id_name
user[0].start_data = u_start_data
user[0].end_data = u_end_data
user[0].mark = u_mark
user[0].type = u_type
user[0].save()
# print(u_name,u_id_name,u_start_data,u_end_data,u_mark,u_type)
# print(type(u_name),type(u_id_name),type(u_start_data),type(u_end_data),type(u_mark),type(u_type))
div = "上传成功"
return render(request,'upload.html',locals())
except Exception:
div = "上传失败,第{}行信息格式填错".format(i)
return render(request, 'upload.html', locals())
div = "请选择excel格式的文件"
return render(request,'upload.html',locals())
return render(request,'upload.html')
02-11 22:21