一、前提

  项目上需求的变更总是时时发生的,应对需求的我们,也只能变更我们代码,所以、继前两篇之后,我们的批量下载诞生了

二、安装

  本文使用zipstream库进行压缩,安装方式:pip install zipstream

  生成Excel方式与前一篇博文一致,这里只是为了讲解下批量下载,需要将多个Excel文件保存,并压缩至一个ZIP文件中即可,所以、关于如何生成Excel文件,本文不再额外介绍,请参考下面的的源码,自行学习。

三、使用

  zipstream使用比较简单,这里直接贴出代码:

  

  1. # coding: UTF-8
  2. import os
  3. import zipstream
  4.  
  5. from web.settings import DOWNLOAD_URL
  6.  
  7. class ZipFile:
  8.  
  9. def __init__(self):
  10. self.folder = DOWNLOAD_URL
  11. for filename in os.listdir(self.folder):
  12. file = self.folder + os.sep + filename
  13. if os.path.exists(file):
  14. os.remove(file)
  15. print('Remove such file:%s' % file)
  16. else:
  17. print('No such file:%s' % file)
  18. self.zipfile = zipstream.ZipFile(mode = 'w', compression = zipstream.ZIP_DEFLATED)
  19.  
  20. def zip_file(self, file, name):
  21. if os.path.isfile(file):
  22. arcname = os.path.basename(file)
  23. self.zipfile.write(file, arcname = arcname)
  24. else:
  25. self.zip_folder(file, name)
  26.  
  27. def zip_folder(self, folder, name = 'downloads'):
  28. for file in os.listdir(folder):
  29. full_path = os.path.join(folder, file)
  30. if os.path.isfile(full_path):
  31. self.zipfile.write(full_path, arcname = os.path.join(name, os.path.basename(full_path)))
  32. elif os.path.isdir(full_path):
  33. self.zip_folder(full_path, os.path.join(name, os.path.basename(full_path)))
  34.  
  35. def close(self):
  36. if self.zipfile:
  37. self.zipfile.close()

四、保存下载

  

  1. excel.save()
  2.  
  3. dt = datetime.datetime.now()
  4. ecarxzip.zip_folder(DOWNLOAD_URL)
  5. response = StreamingHttpResponse(ecarxzip.zipfile, content_type = 'application/zip')
  6. response['Content-Disposition'] = 'attachment;filename={} {}.zip'.format("Batch report", dt.strftime(' %Y-%m-%d %H-%M-%S'))
  7. print("end batch downloading...")
  8. return response

贴下源码:

  1. def batch_download(request, task_id):
  2. print("batch start downloading...", task_id)
  3.  
  4. ai_task = AITask.objects.get(id = task_id)
  5. if 1 == ai_task.type:
  6. domains = Classification.objects.values('domain_name').distinct().filter(type = 1).order_by("domain_name")
  7. elif 2 == ai_task.type:
  8. domains = Classification.objects.values('domain_name').distinct().filter(type = 2).order_by("domain_name")
  9. else:
  10. domains = {}
  11.  
  12. summary_title = ['Domain', 'Pass', 'Fail']
  13. summary_dict = {title: [] for title in summary_title}
  14. domain_title = ['Domain', 'One level', 'Two level', 'Semantic', 'Priority', 'Intent group', 'Intent', 'Result',
  15. 'Handle time', 'Response time', 'Server Domain', 'Detail']
  16.  
  17. sheet_data = {}
  18. ecarxzip = ZipFile() #保存Excel文档前,清空downloads文件夹
  19. for domain in domains:
  20. domain_name = domain["domain_name"]
  21. reports = ai_task.report.filter(semantic__classification__domain_name__exact = domain_name)
  22.  
  23. if len(reports):
  24. pass_no = fail_no = 0
  25. for report in reports:
  26. semantic = report.semantic
  27. classification = semantic.classification
  28. sheet_name = classification.third_classification_Number if classification.third_classification_Number else domain_name
  29. if sheet_name not in sheet_data:
  30. sheet_data[sheet_name] = {title: [] for title in domain_title}
  31.  
  32. sheet_data[sheet_name][domain_title[0]].append(classification.domain_name)
  33. sheet_data[sheet_name][domain_title[1]].append(classification.first_classification)
  34. sheet_data[sheet_name][domain_title[2]].append(classification.second_classification)
  35. sheet_data[sheet_name][domain_title[3]].append(semantic.name)
  36. sheet_data[sheet_name][domain_title[4]].append(classification.semantic_property)
  37. sheet_data[sheet_name][domain_title[5]].append(classification.intent_group)
  38. sheet_data[sheet_name][domain_title[6]].append(classification.intent)
  39. sheet_data[sheet_name][domain_title[7]].append(report.result)
  40. sheet_data[sheet_name][domain_title[8]].append(report.in_handle_time)
  41. sheet_data[sheet_name][domain_title[9]].append(report.ex_handle_time)
  42. sheet_data[sheet_name][domain_title[10]].append(report.server_domain)
  43. sheet_data[sheet_name][domain_title[11]].append(report.description)
  44.  
  45. if "pass" == report.result:
  46. pass_no += 1
  47. elif "fail" == report.result:
  48. fail_no += 1
  49.  
  50. excel = pandas.ExcelWriter('{}/{}.xlsx'.format(DOWNLOAD_URL, domain_name), engine = 'xlsxwriter')
  51. workbook = excel.book
  52. body_format = workbook.add_format(style.body_style)
  53. header_format = workbook.add_format(style.head_style)
  54. long_text_format = workbook.add_format(style.long_text_style)
  55. large_text_format = workbook.add_format(style.large_text_style)
  56.  
  57. summary_data = [domain_name, pass_no, fail_no]
  58. summary_df = pandas.DataFrame({})
  59. summary_df.to_excel(excel, sheet_name = "Summary", index = False, header = False)
  60. worksheet = excel.sheets['Summary']
  61. for index in range(len(summary_title)):
  62. worksheet.write(0, index, summary_title[index], header_format)
  63. worksheet.write(1, index, summary_data[index], body_format)
  64.  
  65. order_sheet = []
  66. for sheet in sheet_data:
  67. order_sheet.append(sheet)
  68.  
  69. order_sheet.sort(key = lambda param: ''.join([no.rjust(2, '') for no in param.split('.')]))
  70. for sheet in order_sheet:
  71. sheet_df = pandas.DataFrame(sheet_data[sheet])
  72. sheet_df.to_excel(excel, sheet_name = sheet, index = False, header = False, startrow = 1)
  73.  
  74. worksheet = excel.sheets[sheet]
  75. worksheet.set_column('A:C', None, body_format)
  76. worksheet.set_column('D:D', 18, long_text_format)
  77. worksheet.set_column('E:E', None, body_format)
  78. worksheet.set_column('F:G', 30, long_text_format)
  79. worksheet.set_column('H:H', None, body_format)
  80. worksheet.set_column('I:K', None, body_format)
  81. worksheet.set_column('L:L', 50, large_text_format)
  82.  
  83. for col, title in enumerate(sheet_df.columns.values):
  84. worksheet.write(0, col, title, header_format)
  85.  
  86. excel.save()
  87. sheet_data.clear() #回收内存
  88.  
  89. summary_dict['Domain'].append(domain_name)
  90. summary_dict['Pass'].append(pass_no)
  91. summary_dict['Fail'].append(fail_no)
  92.  
  93. excel = pandas.ExcelWriter('{}/Summary.xlsx'.format(DOWNLOAD_URL), engine = 'xlsxwriter')
  94.  
  95. summary_df = pandas.DataFrame({})
  96. summary_df.to_excel(excel, sheet_name = 'Summary', index = False, startrow = 1)
  97.  
  98. workbook = excel.book
  99. body_format = workbook.add_format(style.body_style)
  100. header_format = workbook.add_format(style.head_style)
  101.  
  102. worksheet = excel.sheets['Summary']
  103. for col in range(len(summary_title)):
  104. title = summary_title[col]
  105. worksheet.write(0, col, title, header_format)
  106. for row in range(len(summary_dict[title])):
  107. worksheet.write(row + 1, col, summary_dict[title][row], body_format)
  108. excel.save()
  109.  
  110. dt = datetime.datetime.now()
  111. ecarxzip.zip_folder(DOWNLOAD_URL)
  112. response = StreamingHttpResponse(ecarxzip.zipfile, content_type = 'application/zip')
  113. response['Content-Disposition'] = 'attachment;filename={} {}.zip'.format("Batch report", dt.strftime(' %Y-%m-%d %H-%M-%S'))
  114. print("end batch downloading...")
  115. return response

  

Python/Django 批量下载Excel的更多相关文章

  1. Python 爬虫批量下载美剧 from 人人影视 HR-HDTV

    本人比較喜欢看美剧.尤其喜欢人人影视上HR-HDTV 的 1024 分辨率的高清双字美剧,这里写了一个脚本来批量获得指定美剧的全部 HR-HDTV 的 ed2k下载链接.并依照先后顺序写入到文本文件, ...

  2. python多线程批量下载远程图片

    python多线程使用场景:多线程采集, 以及性能测试等 . 数据库驱动类-简单封装下 mysqlDriver.py #!/usr/bin/python3 #-*- coding: utf-8 -*- ...

  3. django 操作 下载 excel xls xlsx csv

    网站开发离不开数据的导入导出,本文将介绍一下django如何操作excel 先安装 django-excel pip install django-excel 配置一下url url(r'^downl ...

  4. python 作业 批量读取excel文件并合并为一张excel

    1 #!/usr/bin/env python 2 # coding: utf-8 3 4 def concat_file(a,b): 5 #如何批量读取并快速合并文件夹中的excel文件 6 imp ...

  5. Java 批量下载excel,并对excel赋值,压缩为zip文件(POI版)

    package com.neusoft.nda.servlet; import java.io.File;import java.io.FileInputStream;import java.io.F ...

  6. 用Python程序批量删除excel里面的图片

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: Rhinoceros PS:如有需要Python学习资料的小伙伴可以 ...

  7. Python爬虫批量下载糗事百科段子,怀念的天王盖地虎,小鸡炖蘑菇...

    欢迎添加华为云小助手微信(微信号:HWCloud002 或 HWCloud003),输入关键字"加群",加入华为云线上技术讨论群:输入关键字"最新活动",获取华 ...

  8. python django 批量上传文件并绑定对应文件的描述

  9. django下载excel,使用django-excel插件

    django下载Excel,使用django-excel插件 由于目前的资料多是使用pandas或xlwt库实现的.其实没有那么的麻烦,因为django有相对应的插件django-excel. 该插件 ...

随机推荐

  1. lucas定理和组合数学

    自湖南长沙培训以来的坑...一直未填,今天把这个问题解决掉. 参考: 1.http://www.cnblogs.com/Var123/p/5523068.html 2.http://blog.csdn ...

  2. 使用Mybatis的逆向工程自动生成代码

    1.逆向工程的作用 Mybatis 官方提供了逆向工程,可以针对数据库表自动生成Mybatis执行所需要的代码(包括mapper.xml.Mapper.java.pojo). 2.逆向工程的使用方法 ...

  3. Nginx学习总结(3)——Nginx配置及应用场景之高级配置

    一.Nginx反向代理 反向代理(Reverse Proxy)方式是指以代理服务器来接受Internet上的连接请求,然后将请求转发给内部网络上的服务器:并将从服务器上得到的结果返回给Internet ...

  4. [codeVS1404] 字符串匹配

    时间限制: 1 s 空间限制: 128000 KB 题目等级 : 大师 Master         题目描述 Description 给你两个串A,B,可以得到从A的任意位开始的子串和B匹配的长度. ...

  5. 0213Zabbix通过percona监控MySQL

    因为Zabbix自带的MySQL监控没有提供可以直接使用的Key,所以一般不采用,业界的同学们都使用Percona Monitoring Plugins 监控 MySQL的方式 Percona介绍 P ...

  6. 洛谷—— P1122 最大子树和

    https://www.luogu.org/problem/show?pid=1122 题目描述 小明对数学饱有兴趣,并且是个勤奋好学的学生,总是在课后留在教室向老师请教一些问题.一天他早晨骑车去上课 ...

  7. Ubuntu源码下载方法

    首先进入: http://cdimage.ubuntu.com/releases/ 选择相应的版本: 进入release页面: http://cdimage.ubuntu.com/releases/1 ...

  8. Ubuntu查看系统版本的方法

    1. less /etc/issue 2. less /proc/version 3. uname -a 4. lsb_release -a

  9. 斯坦福《机器学习》Lesson8感想-------1、SMO

    从上一篇文章可知支持向量(supervector)就是指的离分隔超平面近期的那些点.整个SVM最须要的步骤是训练分类器.得到alpha,从而得到整个用于数据分类的分隔超平面.支持向量机(super v ...

  10. OpenCV2马拉松第25圈——直线拟合与RANSAC算法

    计算机视觉讨论群162501053 转载请注明:http://blog.csdn.net/abcd1992719g/article/details/28118095 收入囊中 最小二乘法(least ...