zoukankan      html  css  js  c++  java
  • django 中下载文件与下载保存为excel

    一、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
  • 相关阅读:
    Last_IO_Error: Got fatal error 1236 from master when reading data from binary log: 'Could not find first log file name in binary log index file'
    ptconfigdiff的使用
    freebsd上安装sudo
    vm9.02的序列号
    pttablechecksum
    "Makefile", line 3: Need an operator
    nc的使用
    vs2005自带的水晶报表破解方法
    [vs2008环境]绑定水晶报表的两种方式(Pull和Push)
    .NET环境下水晶报表使用总结
  • 原文地址:https://www.cnblogs.com/xibuhaohao/p/10419105.html
Copyright © 2011-2022 走看看