sanic实现⽹页上excel导出#!/usr/bin/env python3
import io
import os
import xlwt
from sanic import response
from sanic import Sanic
app = Sanic(__name__)
@ute("/")
def excel_export(request):
fp = excel_gen()
http_response = response.HTTPResponse(body_value(),
headers={'Content-Disposition':'attachment;filename="test.xls"'},
content_type='application/vnd.ms-excel')
return http_response
def excel_gen():
"""
导出excel表格
"""
# 创建⼯作薄
wb = xlwt.Workbook(encoding='gbk')
ws = wb.add_sheet("Sheet1")
# 设置标题⾏
rows_title =['uid','昵称','地区','⽇期']
for i, rows in enumerate(rows_title):
ws.write(0, i, rows, set_style(bg_color='gray40'))
# 设置每列的列宽
for i in range(4):
# 写⼊正⽂
content =[[1,'tom','上海'],
[2,'jerry','北京']]
for i, row in enumerate(content):
for j, col in enumerate(row):
ws.write(i+1, j, col, set_style())
# 将1,2⾏的第4列合并
ws.write_merge(1,2,3,3,'2020-03-01', set_style())
# 保存⽂件到服务器,不需要可以注释掉
# exist_file = ists("test.xls")
# if exist_file:
# os.remove(r"test.xls")
# ws.save("test.xls")
# 将excel⽂件以⼆进制的⽅式存进io
fp = io.BytesIO()
wb.save(fp)
fp.seek(0)
return fp
def set_style(name='宋体', height=240, bold=False, format_str='', align='center', bg_color=''): """设置表格样式"""
"""设置表格样式"""
style = xlwt.XFStyle()# 初始化样式
网页app# 设置背景颜⾊
if bg_color:
pattern = xlwt.Pattern()# ⼀个实例化的样式类
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # 固定的样式
pattern.pattern_fore_colour = lour_map[bg_color]# 背景颜⾊ style.pattern = pattern
# 设置字体样式
font = xlwt.Font()
font.name = name # '宋体'
font.bold = bold
font.height = height # 12*20 12为⼤⼩,20为衡量单位
style.font = font
# 设置排列
alignment = xlwt.Alignment()
if align =='center':
alignment.horz = xlwt.Alignment.HORZ_CENTER # ⽔平分布,左右居中 alignment.vert = xlwt.Alignment.VERT_CENTER # 垂直分布,上下居中else:
alignment.horz = xlwt.Alignment.HORZ_LEFT # ⽔平分布,左对齐
alignment.vert = xlwt.Alignment.VERT_BOTTOM # 垂直分布,往下
style.alignment = alignment
# 为样式创建边框
borders = xlwt.Borders()
borders.left =2
borders.right =2
borders.bottom =2
style.borders = borders
# 设置字符串格式
style.num_format_str = format_str
return style
if __name__ =="__main__":
app.run(host="0.0.0.0", port=8888)
⽣成的excel⽂件
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论