问题:导出文件时,如何将字节流返回给前端,前端通过blob方式获取
方法:
Tornado
import xlwt
from io import BytesIO
class ApiDownloadHandler(BaseHandler):
@login_required()
def post(self):
# 设置响应头
self.set_header('Content-Type', 'application/x-xls')
# filename 不能为中文
self.set_header('Content-Disposition', 'attachment; filename=download.xls')
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
style0 = xlwt.easyxf('font: name Microsoft YaHei Light, height 220; align: vert centre, horiz center')
# title
header = ['序号', '姓名', '年龄']
for i in range(len(header)):
ws.write(0, i, header[i], style0)
ws.col(i).width = 4000
sio = BytesIO()
# 这点很重要,传给save函数的不是保存文件名,而是一个StringIO流
wb.save(sio)
self.write(sio.getvalue())
FastAPI
from io import BytesIO
from fastapi.responses import StreamingResponse
@router.post(
path='/api/export/students',
name='导出学生列表',
description='根据条件筛选学生,并导出为excel文件')
async def export_students(
schema_data: StudentSearchSchema,
db: AsyncSession=Depends(get_async_db),
current_user: UserSchema = Depends(permission('学生基础信息管理', ['operate']))
):
# 将数据写入excel
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
style_header = xlwt.easyxf('font: name Microsoft YaHei Light, height 220, bold true; align: vert centre, horiz left')
style0 = xlwt.easyxf('font: name Microsoft YaHei Light, height 220; align: vert centre, horiz left')
header = ['姓名', '曾用名', '性别']
for i in range(len(header)):
ws.write(0, i, header[i], style_header)
sio = BytesIO()
wb.save(sio)
return StreamingResponse(BytesIO(sio.getvalue()))
参考:
https://blog.csdn.net/x1131230123/article/details/134832957