当前位置:网站首页>Batch export excel zip using zipfile, openpyxl and flask
Batch export excel zip using zipfile, openpyxl and flask
2022-06-22 15:54:00 【mtl1994】
Use zipfile、openpyxl、flask Batch export excel zip
List of articles
Preface
One 、python Use openpyxl operation excel https://blog.csdn.net/mtl1994/article/details/123349397
One 、 Environmental Science
- python3.10 (https://docs.python.org/3/library/zipfile.html)
Two 、 Use
1. Compress local files
with ZipFile('spam.zip', 'w') as myzip:
myzip.write('1.xls')
myzip.write('app.py')
2. Compress stream file to zip
xls_byte = io.BytesIO()
xls_tmp = load_workbook('1.xlsx')
xls_tmp.save(xls_byte)
with ZipFile('spam.zip', 'w') as myzip:
myzip.writestr('1.xlsx', xls_byte.getvalue())
xls_byte.seek(0)
3. Compressed directory pyc
project = PyZipFile("project.zip", mode='w')
project.writepy("d:/datasets-work")
4.openpyxl Generate multiple excel, excel zipfile Compress flask Interface export
@admin.route("/export_all_tmplate", methods=["GET"])
def export_all_tmplate():
all_zip = BytesIO()
zf = ZipFile(all_zip, 'w')
for i in range(10):
output = BytesIO()
wb_tmp = load_workbook(f'tmp-{i}.xlsx')
wb_tmp.save(output)
"""
operation excel...
"""
zf.writestr(f"tmp-{i}.xlsx", output.getvalue())
output.seek(0)
zf.close()
all_zip.seek(0)
resp = make_response(all_zip.getvalue())
basename = 'all.zip'
# transcoding , Support Chinese name
resp.headers["Content-Disposition"] = "attachment; filename*=UTF-8''{utf_filename}".format(
utf_filename=basename)
resp.headers['Content-Type'] = 'application/zip'
return resp
5. example
@admin.route("/equipment_standing_book/basic/export_all_tmplate", methods=["GET"])
# @need_login
# @cache.cached(timeout=600, key_prefix=make_cache_key)
def equipment_standing_book_export_all_tmplate():
"""
#group Export interface
#name Export interface
#desc export excel
#param tmp_name # Template name
#priv need_login
#return data <dict> Notes for each field
#example
{
"code": 0,
"msg": " success ",
"data":{}
}
"""
tmp_name = str(g.request_data.get("tmp_name", "")).strip()
time = str(g.request_data.get("time", "")).strip()
filename = time
tmplate = equip_standing_config.query({'tmp_name': tmp_name})[0]
format = "%Y"
if tmplate['type'] == '3':
format = "%Y-%m"
all_zip = BytesIO()
zf = ZipFile(all_zip, 'w')
record_list = equip_standing_record.query(where=f" and config_id='{tmplate['id']}' and date_format(create_time, '{format}') = '{time}'")
last_record_time = ""
for ri, record in enumerate(record_list):
output = BytesIO()
# If the same date is merged into one excel, many sheet
if last_record_time != "" and last_record_time == record["create_time"].strftime('%Y-%m-%d'):
ws = wb_tmp["next"]
ws.title = record['code'].replace(":", "")
target = wb_tmp.copy_worksheet(wb_tmp.active)
target.title = "next"
else:
wb_tmp = load_workbook(f'./src/statics/{tmp_name}.xlsx')
ws = wb_tmp[wb_tmp.sheetnames[0]]
ws.title = record['code'].replace(":", "")
target = wb_tmp.copy_worksheet(wb_tmp.active)
target.title = "next"
detail_list = eval(tmp_name).query({'record_id': record['id']})
obj: {} = eval(tmp_name).get_dict()
start, start_row, points = 0, [], {}
# Find out which line to assign from excel in Configure the fields corresponding to the entity class
for i, row in enumerate(ws.values):
print(type(row))
start_row = row
for j, value in enumerate(row):
print(i,j,value)
if value in obj.keys():
points[j] = value
start = i
if value == 'serial_number':
points[j] = 'serial_number'
start = i
if start > 0:
break
ws.delete_rows(start + 1)
ws.insert_rows(start + 1, len(detail_list))
# assignment
for i, obj in enumerate(detail_list):
for point in points.keys():
cell = ws.cell(row=start + 1, column=point + 1)
cell.value = i if points[point] == 'serial_number' else obj[points[point]]
cell.border = Border(top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'),
left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'))
start += 1
# If the current line is the same as the previous line , Merge
for i in range(start + 1, ws.max_row + 1):
ws.merge_cells(start_row=i, start_column=1, end_row=i, end_column=ws.max_column)
if (ri + 1 < len(record_list) and record_list[ri + 1]["create_time"].strftime('%Y-%m-%d') != record_list[ri]["create_time"].strftime('%Y-%m-%d'))\
or (last_record_time != "" and last_record_time != record["create_time"].strftime('%Y-%m-%d')):
wb_tmp.remove(wb_tmp["next"])
wb_tmp.save(output)
zf.writestr(record['create_time'].strftime('%Y-%m-%d') + ".xlsx", output.getvalue())
output.seek(0)
last_record_time = record["create_time"].strftime('%Y-%m-%d')
zf.close()
all_zip.seek(0)
resp = make_response(all_zip.getvalue())
basename = f'{filename}.zip'
# transcoding , Support Chinese name
resp.headers["Content-Disposition"] = "attachment; filename*=UTF-8''{utf_filename}".format(
utf_filename=basename)
resp.headers['Content-Type'] = 'application/zip'
return resp
summary
~~~
边栏推荐
- Promouvoir l'adaptation compatible et permettre le développement collaboratif du Service Express adaptatif gbase en mai
- The IPO of Tian'an technology was terminated: Fosun and Jiuding were shareholders who planned to raise 350million yuan
- C # implements insertion sorting
- 华为云HCDEZ专场暨分布式技术峰会:华为云分布式云原生技术与实践之路
- 关于 GIN 的路由树
- 问一下想获取到sqlserver的start_lsn有好的办法吗?
- 极致效率,云原生数据库TDSQL-C安身立命的根本
- 向量6(继承)
- The 12 SQL optimization schemes summarized by professional "brick moving" old drivers are very practical!
- 华为机器学习服务银行卡识别功能,一键实现银行卡识别与绑定
猜你喜欢
![[Newman] postman generates beautiful test reports](/img/5c/b95c1c475e69d69acad75215ea9565.png)
[Newman] postman generates beautiful test reports

【VTK】模型旋转平移
The MIHA tour club in June is hot! 500+ posts, more than HC, just this summer (with internal promotion method)

Jenkins automatically triggers compilation by checking code submissions

Meet webassembly again

【单片机】【让蜂鸣器发声】认识蜂鸣器,让蜂鸣器发出你想要的声音

Scala language learning-05-a comparison of the efficiency of recursion and tail recursion

【一起上水硕系列】Day Three - video

极致效率,云原生数据库TDSQL-C安身立命的根本

FPGA collects DHT11 temperature and humidity
随机推荐
MongoDB在腾讯零售优码中的应用
stack和queue的模拟实现
类似attention nlp
TDengine 连接器上线 Google Data Studio 应用商店
Cve-2022-0847 (privilege lifting kernel vulnerability)
Discover the number of media new users can insert
OOP 多重收纳(类模板)
关于 GIN 的路由树
『忘了再学』Shell流程控制 — 38、while循环和until循环介绍
程序替换函数
HMS core news industry solution: let technology add humanistic temperature
Be an we media video blogger, and share the necessary 32 material websites
Tdengine connector goes online Google Data Studio store
阿里云中间件的开源往事
HMS Core新闻行业解决方案:让技术加上人文的温度
信创研究:国产数据库聚焦信创市场,华为Gauss有望成为最强
Merge sort of sorting
润迈德医疗通过聆讯:年内亏损6.3亿 平安资本是股东
米哈游六月社招火热开启!500+岗位,超多HC,就在这个夏天(附内推方式)
On the routing tree of gin