一、前提

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

二、安装

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

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

三、使用

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

  

# coding: UTF-8
import os
import zipstream from web.settings import DOWNLOAD_URL class ZipFile: def __init__(self):
self.folder = DOWNLOAD_URL
for filename in os.listdir(self.folder):
file = self.folder + os.sep + filename
if os.path.exists(file):
os.remove(file)
print('Remove such file:%s' % file)
else:
print('No such file:%s' % file)
self.zipfile = zipstream.ZipFile(mode = 'w', compression = zipstream.ZIP_DEFLATED) def zip_file(self, file, name):
if os.path.isfile(file):
arcname = os.path.basename(file)
self.zipfile.write(file, arcname = arcname)
else:
self.zip_folder(file, name) def zip_folder(self, folder, name = 'downloads'):
for file in os.listdir(folder):
full_path = os.path.join(folder, file)
if os.path.isfile(full_path):
self.zipfile.write(full_path, arcname = os.path.join(name, os.path.basename(full_path)))
elif os.path.isdir(full_path):
self.zip_folder(full_path, os.path.join(name, os.path.basename(full_path))) def close(self):
if self.zipfile:
self.zipfile.close()

四、保存下载

  

    excel.save()

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

贴下源码:

def batch_download(request, task_id):
print("batch start downloading...", task_id) ai_task = AITask.objects.get(id = task_id)
if 1 == ai_task.type:
domains = Classification.objects.values('domain_name').distinct().filter(type = 1).order_by("domain_name")
elif 2 == ai_task.type:
domains = Classification.objects.values('domain_name').distinct().filter(type = 2).order_by("domain_name")
else:
domains = {} summary_title = ['Domain', 'Pass', 'Fail']
summary_dict = {title: [] for title in summary_title}
domain_title = ['Domain', 'One level', 'Two level', 'Semantic', 'Priority', 'Intent group', 'Intent', 'Result',
'Handle time', 'Response time', 'Server Domain', 'Detail'] sheet_data = {}
ecarxzip = ZipFile() #保存Excel文档前,清空downloads文件夹
for domain in domains:
domain_name = domain["domain_name"]
reports = ai_task.report.filter(semantic__classification__domain_name__exact = domain_name) if len(reports):
pass_no = fail_no = 0
for report in reports:
semantic = report.semantic
classification = semantic.classification
sheet_name = classification.third_classification_Number if classification.third_classification_Number else domain_name
if sheet_name not in sheet_data:
sheet_data[sheet_name] = {title: [] for title in domain_title} sheet_data[sheet_name][domain_title[0]].append(classification.domain_name)
sheet_data[sheet_name][domain_title[1]].append(classification.first_classification)
sheet_data[sheet_name][domain_title[2]].append(classification.second_classification)
sheet_data[sheet_name][domain_title[3]].append(semantic.name)
sheet_data[sheet_name][domain_title[4]].append(classification.semantic_property)
sheet_data[sheet_name][domain_title[5]].append(classification.intent_group)
sheet_data[sheet_name][domain_title[6]].append(classification.intent)
sheet_data[sheet_name][domain_title[7]].append(report.result)
sheet_data[sheet_name][domain_title[8]].append(report.in_handle_time)
sheet_data[sheet_name][domain_title[9]].append(report.ex_handle_time)
sheet_data[sheet_name][domain_title[10]].append(report.server_domain)
sheet_data[sheet_name][domain_title[11]].append(report.description) if "pass" == report.result:
pass_no += 1
elif "fail" == report.result:
fail_no += 1 excel = pandas.ExcelWriter('{}/{}.xlsx'.format(DOWNLOAD_URL, domain_name), engine = 'xlsxwriter')
workbook = excel.book
body_format = workbook.add_format(style.body_style)
header_format = workbook.add_format(style.head_style)
long_text_format = workbook.add_format(style.long_text_style)
large_text_format = workbook.add_format(style.large_text_style) summary_data = [domain_name, pass_no, fail_no]
summary_df = pandas.DataFrame({})
summary_df.to_excel(excel, sheet_name = "Summary", index = False, header = False)
worksheet = excel.sheets['Summary']
for index in range(len(summary_title)):
worksheet.write(0, index, summary_title[index], header_format)
worksheet.write(1, index, summary_data[index], body_format) order_sheet = []
for sheet in sheet_data:
order_sheet.append(sheet) order_sheet.sort(key = lambda param: ''.join([no.rjust(2, '') for no in param.split('.')]))
for sheet in order_sheet:
sheet_df = pandas.DataFrame(sheet_data[sheet])
sheet_df.to_excel(excel, sheet_name = sheet, index = False, header = False, startrow = 1) worksheet = excel.sheets[sheet]
worksheet.set_column('A:C', None, body_format)
worksheet.set_column('D:D', 18, long_text_format)
worksheet.set_column('E:E', None, body_format)
worksheet.set_column('F:G', 30, long_text_format)
worksheet.set_column('H:H', None, body_format)
worksheet.set_column('I:K', None, body_format)
worksheet.set_column('L:L', 50, large_text_format) for col, title in enumerate(sheet_df.columns.values):
worksheet.write(0, col, title, header_format) excel.save()
sheet_data.clear() #回收内存 summary_dict['Domain'].append(domain_name)
summary_dict['Pass'].append(pass_no)
summary_dict['Fail'].append(fail_no) excel = pandas.ExcelWriter('{}/Summary.xlsx'.format(DOWNLOAD_URL), engine = 'xlsxwriter') summary_df = pandas.DataFrame({})
summary_df.to_excel(excel, sheet_name = 'Summary', index = False, startrow = 1) workbook = excel.book
body_format = workbook.add_format(style.body_style)
header_format = workbook.add_format(style.head_style) worksheet = excel.sheets['Summary']
for col in range(len(summary_title)):
title = summary_title[col]
worksheet.write(0, col, title, header_format)
for row in range(len(summary_dict[title])):
worksheet.write(row + 1, col, summary_dict[title][row], body_format)
excel.save() dt = datetime.datetime.now()
ecarxzip.zip_folder(DOWNLOAD_URL)
response = StreamingHttpResponse(ecarxzip.zipfile, content_type = 'application/zip')
response['Content-Disposition'] = 'attachment;filename={} {}.zip'.format("Batch report", dt.strftime(' %Y-%m-%d %H-%M-%S'))
print("end batch downloading...")
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. linux which-查找并显示给定命令的绝对路径

    推荐:更多Linux 文件查找和比较 命令关注:linux命令大全 which命令用于查找并显示给定命令的绝对路径,环境变量PATH中保存了查找命令时需要遍历的目录.which指令会在环境变量$PAT ...

  2. noip模拟赛 dwarf tower

    [问题描述]Vasya在玩一个叫做"Dwarf Tower"的游戏,这个游戏中有n个不同的物品,它们的编号为1到n.现在Vasya想得到编号为1的物品.获得一个物品有两种方式:1. ...

  3. windows server 2008R2 上安装配置freesshd

    从FREESSHD官方网站下载最新的软件版本,下载地址是http://www.freesshd.com/?ctt=download 双击刚刚下载的freeSSHd.exe进行安装,安装时其他都是默认安 ...

  4. MySQL Workbench查看和修改表字段的Comment值

    查看: 选择单个表->[右键]->[Table Inspector] 再选择Columns选项卡即可,把表格拉倒最后一列. 编辑: 选择单个表->[右键]->[Alter Ta ...

  5. python列表可以加可以乘

    python列表可以加可以乘 list=['abcd',786,2.23,'runoob',70.2] tinylist = [123,'runoob'] print(list) print(list ...

  6. ROBODK仿真如何设置运动速度

    设置工具-选项-运动,把仿真时间设置成跟正常一样   然后双击机器人,设置参数(可以设置movej和movel的速度,加速度)  

  7. 使用Code First建模自引用关系笔记 asp.net core上使用redis探索(1) asp.net mvc控制器激活全分析 语言入门必学的基础知识你还记得么? 反射

    使用Code First建模自引用关系笔记   原文链接 一.Has方法: A.HasRequired(a => a.B); HasOptional:前者包含后者一个实例或者为null HasR ...

  8. C#之插入排序

    算法描述 1.假定数组第一位为有序序列,抽出后一位元素与有序序列中元素依次比较: 2.如果有序序列元素大于抽出元素,将该元素向后移位: 3.重复前面步骤依次抽取无序序列中首位元素进行比较,直到所有数值 ...

  9. LeetCode 1002. Find Common Characters (查找常用字符)

    题目标签:Array, Hash Table 题目给了我们一个string array A,让我们找到common characters. 建立一个26 size 的int common array, ...

  10. LeetCode 21. Merge Two Sorted Lists (合并两个有序链表)

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t ...