Flask + xlwt 以流形式返回Excel文件

发布时间 2023-08-18 11:02:32作者: 南有嘉木

flask

from io import BytesIO
import xlwt
from flask import send_file

@app.route('/')
def get_excel():
	bio = BytesIO()
	wb = xlwt.Workbook(encoding='utf8')
	sheet = wb.add_sheet('Sheet1',cell_overwrite_ok=True)
	# 写入表头	
	styleOK = xlwt.easyxf()
	pattern = xlwt.Pattern()  # 一个实例化的样式类
	pattern.pattern = xlwt.Pattern.SOLID_PATTERN  # 固定的样式
	pattern.pattern_fore_colour = xlwt.Style.colour_map['yellow']  # 背景颜色
	styleOK.pattern = pattern
	header = ['姓名','手机号']
	keys = ['name','phone_no']
	for i,val in enumerate(header):
		sheet.write(0, i, val,style=styleOK)
	# 写入数据
	for index, row in enumerate(res):
		for j, key in enumerate(keys):
    			sheet.write(index+1, j, str(row[key]))
	wb.save(bio)
	bio.seek(0)
	return send_file(bio, as_attachment=True, attachment_filename="ab.xlsx")

vue

fetch().then(res => {
	const blob = new Blob([res.data])
        const fileName = 'ab.xls'
        const elink = document.createElement('a')// 创建a标签
        elink.download = fileName// 为a标签添加download属性
        // a.download = fileName; //命名下载名称
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()// 点击下载
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)// 释放标签
})