Created
August 16, 2021 05:33
-
-
Save feiandxs/64ec68c214ff5389c46761aa8926c12e to your computer and use it in GitHub Desktop.
fastapi输出xls 下载
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI | |
from fastapi.responses import Response | |
import xlwt | |
from io import BytesIO | |
app = FastAPI() | |
@app.get("/") | |
async def root(): | |
# list = [ | |
# { | |
# "a": 1, | |
# "b": 2 | |
# } | |
# ] | |
wb = xlwt.Workbook(encoding='utf-8') # 实例化,有encoding和style_compression参数 | |
ws = wb.add_sheet("111", cell_overwrite_ok=True) # Workbook的方法,生成名为111.xls文件 | |
row0 = ['create_time', 'sign_status', 'name', 'sfz', 'phone'] # 指定xls文件的字段 | |
for i in range(0, len(row0)): # 将这些字段写入111.xls文件 | |
ws.write(0, i, row0[i]) | |
k = 1 | |
for i in r: | |
# for j in range(4): | |
# ws.write(k, j, i[4]) | |
ws.write(k, 0, i['create_time']) | |
ws.write(k, 1, i['sign_status']) | |
ws.write(k, 2, i['name']) | |
ws.write(k, 3, i['sfz']) | |
ws.write(k, 4, i['phone']) | |
k += 1 | |
sio = BytesIO() # 将获取的数据在内存中写,有时会用到StringIO() | |
wb.save(sio) # 将文件流保存 | |
sio.seek(0) # 光标 | |
return Response(content=sio.read(), media_type='application/vnd.ms-excel') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment