一、django 中下载文件

在实际的项目中很多时候需要用到下载功能,如导excel、pdf或者文件下载,当然你可以使用web服务自己搭建可以用于下载的资源服务器,如nginx,这里我们主要介绍django中的文件下载。

1、前端

实现方式:a标签+响应头信息(当然你可以选择form实现)

<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >点我下载</a></div>

2、Url

路由url:
url(r'^download/',views.download,name="download"),

3、后端

方式一:使用HttpResponse
views.py代码
from django.shortcuts import HttpResponse
def download(request):
  file = open('crm/models.py', 'rb')
  response = HttpResponse(file)
  response['Content-Type'] = 'application/octet-stream' #设置头信息,告诉浏览器这是个文件
  response['Content-Disposition'] = 'attachment;filename="models.py"'
  return response
方式二:使用StreamingHttpResponse
其他逻辑不变,主要变化在后端处理
from django.http import StreamingHttpResponse
def download(request):
  file=open('crm/models.py','rb')
  response =StreamingHttpResponse(file)
  response['Content-Type']='application/octet-stream'
  response['Content-Disposition']='attachment;filename="models.py"'
  return response
方式三:使用FileResponse
from django.http import FileResponse
def download(request):
  file=open('crm/models.py','rb')
  response =FileResponse(file)
  response['Content-Type']='application/octet-stream'
  response['Content-Disposition']='attachment;filename="models.py"'
  return response
使用总结
三种http响应对象在django官网都有介绍.入口:https://docs.djangoproject.com/en/1.11/ref/request-response/
推荐使用FileResponse,从源码中可以看出FileResponse是StreamingHttpResponse的子类,内部使用迭代器进行数据流传输。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
 

二、django导出excel文件

1、前端

实现方式:a标签+响应头信息(当然你可以选择form实现)
<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >点我下载</a></div>

2、Url

路由url:
url(r'^download/',views.download,name="download"),

3、后端

# 导入render和HttpResponse模块
from django.shortcuts import render, HttpResponse
from io import BytesIO
import xlwt
# 导出excel数据
def download(request):
# 设置HTTPResponse的类型
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment;filename=test.xls'
# 创建一个文件对象
wb = xlwt.Workbook(encoding='utf8')
# 创建一个sheet对象
sheet = wb.add_sheet('order-sheet') # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改
style_heading = xlwt.easyxf("""
font:
name Arial,
colour_index white,
bold on,
height 0xA0;
align:
wrap off,
vert center,
horiz center;
pattern:
pattern solid,
fore-colour 0x19;
borders:
left THIN,
right THIN,
top THIN,
bottom THIN;
""") # 写入文件标题
sheet.write(0, 0, '申请编号', style_heading)
sheet.write(0, 1, '客户名称', style_heading)
sheet.write(0, 2, '联系方式', style_heading)
sheet.write(0, 3, '身份证号码', style_heading)
sheet.write(0, 4, '办理日期', style_heading)
sheet.write(0, 5, '处理人', style_heading)
sheet.write(0, 6, '处理状态', style_heading)
sheet.write(0, 7, '处理时间', style_heading) # 写入数据
data_row = 1
# UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.
a=models.UserTable.objects.all()
print(a)
for i in models.UserTable.objects.all():
# 格式化datetime
pri_time = i.pri_date.strftime('%Y-%m-%d')
oper_time = i.operating_time.strftime('%Y-%m-%d')
sheet.write(data_row, 0, i.loan_id)
sheet.write(data_row, 1, i.name)
sheet.write(data_row, 2, i.user_phone)
sheet.write(data_row, 3, i.user_card)
sheet.write(data_row, 4, pri_time)
sheet.write(data_row, 5, i.emp.emp_name)
sheet.write(data_row, 6, i.statu.statu_name)
sheet.write(data_row, 7, oper_time)
data_row = data_row + 1 # 写入数据,使用原生SQL方式
????????????????? # 写出到IO
output = BytesIO()
wb.save(output)
# 重新定位到开始
output.seek(0)
response.write(output.getvalue())
return response
 
整理自:
https://www.jb51.net/article/137790.htm
https://blog.csdn.net/qq_33196814/article/details/81486843

django 中下载文件与下载保存为excel的更多相关文章

  1. CEfSharp下载文件 弹出保存框,实现 IDownloadHandler 接口

    上节讲了如何将CefSharp集成到C#中,但集成后将web界面链接进ChromiumWebBrowser后,但web界面上下载附件的功能不好使咯. 百度了半天还是没搞定,只能去看官网的Excampl ...

  2. 使用CEfSharp之旅(3)下载文件 弹出保存框 IDownloadHandler

    原文:使用CEfSharp之旅(3)下载文件 弹出保存框 IDownloadHandler 版权声明:本文为博主原创文章,未经博主允许不得转载.可点击关注博主 ,不明白的进群191065815 我的群 ...

  3. AFHTTPSessionManager下载文件 及下载中 进度条处理,进度条处理需要特别注意,要加载NSRunLoop 中

    1.下载文件 和进度条处理代码 - (void)timer:(NSTimer *)timer{ // 另一个View中 进度条progress属性赋值 _downloadView.progress = ...

  4. 利用(CMD)在Django中创建文件

    django项目的创建(在CMD中) 1.切换到你想要存储项目的位置,我这里保存在桌面上 cd Desktop 2.创建一个django项目,项目名叫guest django-admin startp ...

  5. django中处理文件上传文件

    1 template模版文件uploadfile.html 特别注意的是,只有当request方法是POST,且发送request的<form>有属性enctype="multi ...

  6. django 中静态文件项目加载问题

    问题描述: django项目中创建了多个app后,每个app中都有对应的static静态文件.整个项目运行时这些静态文件的加载就是一个问题,因为整个项目我只参与了一部分,项目部署之类的并没有参与.我写 ...

  7. django中migration文件是干啥的

    昨天很蠢的问leader git push的时候会不会把本地的数据库文件上传上去,意思是django中那些migration文件修改之后会不会上传. 然后得知不会,因为所有的数据库都存在本机的mysq ...

  8. Django中静态文件引用优化

    静态文件引用优化 在html文件中是用django的静态文件路径时,一般会这么写: <script type="text/javascript" src="/sta ...

  9. php 下载文件/直接下载数据内容

    思路步骤 * 定义参数 * 魔术方法 * 执行下载 * 获取设置属性函数 * 获取设置文件mime 类型 * 获取设置下载文件名 * 设置header * 下载函数 实现代码 class DownFi ...

随机推荐

  1. JS中UTF-8和UTF-16互转

    1.由于服务端使用的Go,默认是使用UTF-8编码的,而JS默认是Unicode编码的(也就是UTF-16),所以为了字符串编码的一致性,将前端字符串数据编码转换为UTF-8之后再发送给服务端,服务端 ...

  2. mui体验理解

    1.      mui简介 1.1  缘起 1.基于jq的jqmobile,性能低的无法忍受,且UI难看 2.bootstrap这种响应式设计,性能在低端机不足,而且UI风格一看就是网页,不是App的 ...

  3. 单调队列 Monotonic Queue / 单调栈 Monotonic Stack

    2018-11-16 22:45:48 一.单调队列 Monotone Queue 239. Sliding Window Maximum 问题描述: 问题求解: 本题是一个经典的可以使用双端队列或者 ...

  4. 日常英语---十四、Dolce & Gabbana cancels China show amid 'racist' ad controversy(adj.温柔的,prep.在其中)

    日常英语---十四.Dolce & Gabbana cancels China show amid 'racist' ad controversy(adj.温柔的,prep.在其中) 一.总结 ...

  5. R语言画点状误差线

    现在项目需要R语言做几个线性拟合,画一些点图,突然需要画误差线,网上找了下,可以用代码实现..效果如下 xx1<-c(xxxxxx,xxxx,xxxxx) yy1<-c(xxxxxx,xx ...

  6. windows10 64bit 下的tensorflow 安装及demo

    目前流行的深度学习库有Caffe,Keras,Theano,本文采用谷歌开源的曾用来制作AlphaGo的深度学习系统Tensorflow. 1:安装Tensorflow 最早TensorFlow只支持 ...

  7. 8.2 DRAM和SRAM

    计算机组成 8 存储层次结构 8.2 DRAM和SRAM SRAM比较快,DRAM比较慢:SRAM比较贵,DRAM比较便宜.记住这些结论是很容易的,但是比是什么更重要的是为什么.那在这一节我们就从电路 ...

  8. 时钟中断TIMER_BH(bottom_half)实现分析

    017-12-6 16:27:35时钟中断TIMER_BH(bottom_half)实现分析1.3.1001. 时钟0号中断安装    setup_x86_irq(0, &irq0);@arc ...

  9. git 提交代码场景

    1.首次提交代码到master git init git add . git commit -m '' git remote add origin +address git push -u origi ...

  10. CentOS6.8环境下搭建yum网络仓库

    CentOS6.8环境下搭建yum网络仓库 本文利用ftp服务,在CentOS6.8系统下搭建一个yum仓库,然后用另一台虚拟机访问该仓库.并安装程序包 安装ftp服务 查询ftp服务是否安装 [ro ...