본문 바로가기
FastAPI tips

Excel 다운로드 API

by 스티브 십잡스 2024. 5. 8.
from fastapi import FastAPI, Request, HTTPException


app = FastAPI()

'''
엑셀 파일 생성
'''
from fastapi.responses import StreamingResponse
import pandas as pd
import openpyxl
from datetime import datetime
from io import BytesIO


async def make_excel_file(cols: list, rows: list) -> StreamingResponse:
    buffer = BytesIO()

    df = pd.DataFrame(data=[rows], columns=cols)

    file_name = f"example_{datetime.now().date()}"
    encoded_file_name = file_name.encode('utf-8').decode('cp949')

    # filename은 front에서도 지정 가능
    headers = {
        "Content-Disposition": f'attachment; filename="{encoded_file_name}.xlsx"',
    }
    with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
        df.to_excel(writer, index=False)

    return StreamingResponse(
        BytesIO(buffer.getvalue()),
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers=headers,
    )

@app.post("/excel")
async def download(command: GetExampleRequest, db: Session = Depends(get_db)):
    # return {"cols": [...], "rows": [...]}
    resp = await example.get_data_for_excel(command=command, db=db) 
    return await excel.make_excel_file(cols=resp['cols'], rows=resp['rows'])

'FastAPI tips' 카테고리의 다른 글

Jinja2 템플릿 활용  (0) 2024.05.08
Middleware 커스텀해서 사용하기  (0) 2024.05.03
UploadFile, 이미지 form-data  (0) 2024.03.28
Request에서 form-data, query-string 가져오기  (0) 2024.03.28