在django项目中导出数据到excel文件并实现下载的功能


Posted in Python onMarch 13, 2020

依赖模块

xlwt下载:pip install xlwt

后台模块

view.py

# 导出Excel文件
def export_excel(request):
  city = request.POST.get('city')
  print(city)
  list_obj=place.objects.filter(city=city)
  # 设置HTTPResponse的类型
  response = HttpResponse(content_type='application/vnd.ms-excel')
  response['Content-Disposition'] = 'attachment;filename='+city+'.xls'
  """导出excel表"""
  if list_obj:
    # 创建工作簿
    ws = xlwt.Workbook(encoding='utf-8')
    # 添加第一页数据表
    w = ws.add_sheet('sheet1') # 新建sheet(sheet的名称为"sheet1")
    # 写入表头
    w.write(0, 0, u'地名')
    w.write(0, 1, u'次数')
    w.write(0, 2, u'经度')
    w.write(0, 3, u'纬度')
    # 写入数据
    excel_row = 1
    for obj in list_obj:
      name = obj.place
      sum = obj.sum
      lng = obj.lng
      lat = obj.lat
      # 写入每一行对应的数据
      w.write(excel_row, 0, name)
      w.write(excel_row, 1, sum)
      w.write(excel_row, 2, lng)
      w.write(excel_row, 3, lat)
      excel_row += 1
    # 写出到IO
    output = BytesIO()
    ws.save(output)
    # 重新定位到开始
    output.seek(0)
    response.write(output.getvalue())
  return response

前端模块

<button id="export_excel" type="button" class="btn btn-primary col-sm-5" style="margin-left: 10px" >导出excel</button>

$("#export_excel").click(function () {
     var csrf=$('input[name="csrfmiddlewaretoken"]').val();
     const req = new XMLHttpRequest();
     req.open('POST', '/export_excel/', true);
     req.responseType = 'blob';
     req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //设置请求头
     req.send('city='+$('#city').val()+"&&csrfmiddlewaretoken="+csrf); //输入参数
     req.onload = function() {
       const data = req.response;
       const a = document.createElement('a');
       const blob = new Blob([data]);
       const blobUrl = window.URL.createObjectURL(blob);
       download(blobUrl) ;
     };

   });
function download(blobUrl) {
 var city = $("input[name='city']").val();
 const a = document.createElement('a');
 a.style.display = 'none';
 a.download = '<文件命名>';
 a.href = blobUrl;
 a.click();
 document.body.removeChild(a);
}

补充知识:Python Django实现MySQL百万、千万级的数据量下载:解决memoryerror、nginx time out

前文

在用Django写项目的时候时常需要提供文件下载的功能,而Django也是贴心提供了几种方法:FileResponse、StreamingHttpResponse、HttpResponse,其中FileResponse和StreamingHttpResponse都是使用迭代器迭代生成数据的方法,所以适合传输文件比较大的情况;而HttpResponse则是直接取得数据返回给用户,所以容易造成memoryerror和nginx time out(一次性取得数据和返回的数据过多,导致nginx超时或者内存不足),关于这三者,DJango的官网也是写的非常清楚,连接如下:https://docs.djangoproject.com/en/1.11/ref/request-response/

那正常我们使用的是FileResponse和StreamingHttpResponse,因为它们流式传输(迭代器)的特点,可以使得数据一条条的返回给客户端,文件随时中断和复传,并且保持文件的一致性。

FileResponse和StreamingHttpResponse

FileResponse顾名思义,就是打开文件然后进行传输,并且可以指定一次能够传输的数据chunk。所以适用场景:从服务端返回大文件。缺点是无法实时获取数据库的内容并传输给客户端。举例如下:

def download(request):
 file=open('path/demo.py','rb')
  response =FileResponse(file)
  response['Content-Type']='application/octet-stream'
  response['Content-Disposition']='attachment;filename="demo.py"'
  return response

从上可以发现,文件打开后作为参数传入FileResponse,随后指定传输头即可,但是很明显用这个来传输数据库就不太方便了,所以这边推介用StreamingHttpResponse的方式来传输。

这里就用PyMysql来取得数据,然后指定为csv的格式返回,具体代码如下:

# 通过pymysql取得数据
import pymysql
field_types = {
    1: 'tinyint',
    2: 'smallint',
    3: 'int'} #用于后面的字段名匹配,这里省略了大多数
conn = pymysql.connect(host='127.0.0.1',port=3306,database='demo',user='root',password='root')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql)
#获取所有数据
data = cursor.fetchall()
cols = {}
#获取所有字段
for i,row in enumerate(self.cursor.description):
 if row[0] in cols:
   cols[str(i)+row[0]] = field_types.get(row[1], str(row[1])) #这里的field_type是类型和数字的匹配
 cols[row[0]] = field_types.get(row[1], str(row[1]))
cursor.close()
conn.close()

#通过StreamingHttpResponse指定返回格式为csv
response = StreamingHttpResponse(get_result_fromat(data, cols))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(out_file_name)
return response

#循环所有数据,然后加到字段上返回,注意的是要用迭代器来控制
def get_result_fromat(data, cols):
 tmp_str = ""
 # 返回文件的每一列列名
  for col in cols:
    tmp_str += '"%s",' % (col)
  yield tmp_str.strip(",") + "\n"
  for row in data:
    tmp_str = ""
    for col in cols:
      tmp_str += '"%s",' % (str(row[col]))
    yield tmp_str.strip(',') + "\n"

整个代码如上,大致分为三部分:从mysql取数据,格式化成我们想要的格式:excel、csv、txt等等,这边指定的是csv,如果对其他格式也有兴趣的可以留言,最后就是用StreamingHttpResponse指定返回的格式返回。

实现百万级数据量下载

上面的代码下载可以支持几万行甚至十几万行的数据,但是如果超过20万行以上的数据,那就比较困难了,我这边的剩余内存大概是1G的样子,当超过15万行数据(大概)的时候,就报memoryerror了,问题就是因为fetchall,虽然我们StreamingHttpResponse是一条条的返回,但是我们的数据时一次性批量的取得!

如何解决?以下是我的解决方法和思路:

用fetchone来代替fetchall,迭代生成fetchone

发现还是memoryerror,因为execute是一次性执行,后来发现可以用流式游标来代替原来的普通游标,即SSDictCursor代替DictCursor

于是整个代码需要修改的地方如下:

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ===>
cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)

data = cursor.fetchall() ===>
row = cursor.fetchone()

def get_result_fromat(data, cols):
 tmp_str = ""
 # 返回文件的每一列列名
  for col in cols:
    tmp_str += '"%s",' % (col)
  yield tmp_str.strip(",") + "\n"
  for row in data:
    tmp_str = ""
    for col in cols:
      tmp_str += '"%s",' % (str(row[col]))
    yield tmp_str.strip(',') + "\n" 
    
    =====>
    
def get_result_fromat(data, cols):
 tmp_str = ""
  for col in cols:
    tmp_str += '"%s",' % (col)
  yield tmp_str.strip(",") + "\n"
  while True:
    tmp_str = ""
    for col in cols:
      tmp_str += '"%s",' % (str(row[col]))
    yield tmp_str.strip(',') + "\n"
    row = db.cursor.fetchone()
    if row is None:
      break

可以看到就是通过while True来实现不断地取数据下载,有效避免一次性从MySQL取出内存不足报错,又或者取得过久导致nginx超时!

总结

关于下载就分享到这了,还是比较简单的,谢谢观看~希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现多线程抓取网页功能实例详解
Jun 08 Python
Python实现基于二叉树存储结构的堆排序算法示例
Dec 08 Python
python3中类的继承以及self和super的区别详解
Jun 26 Python
在cmd中查看python的安装路径方法
Jul 03 Python
python如何删除文件中重复的字段
Jul 16 Python
简单了解django索引的相关知识
Jul 17 Python
图文详解Django使用Pycharm连接MySQL数据库
Aug 09 Python
Python 写了个新型冠状病毒疫情传播模拟程序
Feb 14 Python
keras实现多GPU或指定GPU的使用介绍
Jun 17 Python
Python命令行参数定义及需要注意的地方
Nov 30 Python
在Python中实现字典反转案例
Dec 05 Python
Pytorch distributed 多卡并行载入模型操作
Jun 05 Python
Django choices下拉列表绑定实例
Mar 13 #Python
django model object序列化实例
Mar 13 #Python
浅析python标准库中的glob
Mar 13 #Python
Python3标准库glob文件名模式匹配的问题
Mar 13 #Python
python编写俄罗斯方块
Mar 13 #Python
探秘TensorFlow 和 NumPy 的 Broadcasting 机制
Mar 13 #Python
自定义Django Form中choicefield下拉菜单选取数据库内容实例
Mar 13 #Python
You might like
模仿OSO的论坛(五)
2006/10/09 PHP
php的闭包(Closure)匿名函数详解
2015/02/22 PHP
PHP pear安装配置教程
2016/05/14 PHP
通过ifame指向的页面高度调整iframe的高度
2006/10/05 Javascript
css配合jquery美化 select
2013/11/29 Javascript
可恶的ie8提示缺少id未定义
2014/03/20 Javascript
jquery实现标题字体变换的滑动门菜单效果
2015/09/07 Javascript
jquery分页插件jquery.pagination.js使用方法解析
2016/04/01 Javascript
SVG动画vivus.js库使用小结(实例代码)
2017/09/14 Javascript
JS内部事件机制之单线程原理
2018/07/02 Javascript
vue v-model实现自定义样式多选与单选功能
2018/07/05 Javascript
vue.js 实现点击展开收起动画效果
2018/07/07 Javascript
jQuery实现获取当前鼠标位置并输出功能示例
2019/01/05 jQuery
浅谈如何优雅处理JavaScript异步错误
2019/11/12 Javascript
Vue2.4+新增属性.sync、$attrs、$listeners的具体使用
2020/03/08 Javascript
Node.js 深度调试方法解析
2020/07/28 Javascript
python的keyword模块用法实例分析
2015/06/30 Python
详解Python开发中如何使用Hook技巧
2017/11/01 Python
python3.6实现学生信息管理系统
2019/02/21 Python
python3实现斐波那契数列(4种方法)
2019/07/15 Python
简单了解为什么python函数后有多个括号
2019/12/19 Python
Django的CVB实例详解
2020/02/10 Python
Python *args和**kwargs用法实例解析
2020/03/02 Python
使用tensorflow框架在Colab上跑通猫狗识别代码
2020/04/26 Python
Python 常用日期处理 -- calendar 与 dateutil 模块的使用
2020/09/02 Python
HTML5 canvas实现雪花飘落特效
2016/03/08 HTML / CSS
经贸日语专业个人求职信
2013/12/13 职场文书
十佳教师事迹材料
2014/01/11 职场文书
店长职务说明书
2014/02/04 职场文书
副总经理岗位职责
2014/03/16 职场文书
行政办公室岗位职责
2014/03/18 职场文书
船舶工程技术专业求职信
2014/08/07 职场文书
祖国在我心中演讲稿200字
2014/08/28 职场文书
2014年幼儿园德育工作总结
2014/12/17 职场文书
2015年12.4全国法制宣传日活动总结
2015/03/24 职场文书
golang 实现并发求和
2021/05/08 Golang