본문 바로가기

BackEnd

FastAPI Excel Download 기능구현

반응형

FastAPI에서 Excel Download 기능을 구현하는 코드

CRUD와 ROUTER만 기재

 

CRUD

def excel_download(seq, db = Session) :
    try :
        # 판다스 데이터프레임을 만들기위한 빈 리스트를 만들어준다
        table_data = []

        # 데이터 추출을 위한 작업을 for문 if문 등을 이용해 작성한다
        # ...

        # 빈 리스트에 딕셔너리형태로 되어있는 데이터를 담아준다
        table_data.append({"a":'a',"b":'b',"c":'c',"d":'d'})

        # 리스트를 df라는 변수명으로 데이터프레임으로 만들어준다
        df = pd.DataFrame(table_data)

        # 판다스의 to_excel 함수를 이용하여 저장해준다
        # 파라미터는 공식문서 참고!
        df.to_excel(excel_writer="./excel.xlsx",sheet_name= date.today().strftime('%Y-%m-%d')+" "+'Report Data')

        # 디렉토리 지정
        ROOT_DIR = './'

        # 파일 이름 지정
        file_name = 'excel.xlsx'
        
        # target_file 지정
        target_file = ROOT_DIR + file_name
       
    finally:
        db.close()

    return FileResponse(target_file, filename=file_name)

 

 

ROUTER

@router.get("/excel/{seq}")
def excel_download(seq , db: Session = Depends(get_db)):
    return crud.excel_download(seq=seq, db=db)

 

Excel Download 기능의 가장 기본적인 방법으로

가상환경, 혹은 개발중인 디렉토리에 파일을 생성하고

그 파일을 브라우저에서 다운로드를 진행하는 코드입니다

 

파일을 다운로드받기 위해서는 터미널에서 명령어를 실행 후 docs에서 테스트를 진행 하는걸 추천드립니다

반응형